本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
設定 Amazon Location 的初始程式碼
此頁面提供與 Amazon Location Service 整合之範例 iOS 應用程式的初始程式碼。使用此程式碼作為起點,您可以利用地圖、地理編碼、地理強制執行、追蹤和路由等功能來建置感知位置的 iOS 應用程式。
在應用程式中啟用位置許可
開啟 Xcode 專案。
找出專案
Info.plist
的檔案。根據您的應用程式需求,為位置許可新增必要的金鑰。以下是金鑰:
NSLocationWhenInUseUsageDescription
:說明應用程式在使用時需要存取位置的原因。NSLocationAlwaysAndWhenInUseUsageDescription
:說明應用程式需要持續存取位置的原因。
現在,您需要在應用程式中設定資源值。新增名為 的新檔案Config.xcconfig
,並填寫您先前在 Amazon 主控台中建立的值。
REGION = INDEX_NAME = MAP_NAME = IDENTITY_POOL_ID = TRACKER_NAME =
從左側導覽器區段中,選取專案。
在目標區段下,選取您的應用程式,然後按一下資訊索引標籤。
使用如下所示的值新增資訊屬性:
新增包含下列內容
Config.swift
的檔案,其將從套件資訊檔案中讀取組態值。import Foundation enum Config { static let region = Bundle.main.object(forInfoDictionaryKey: "Region") as! String static let mapName = Bundle.main.object(forInfoDictionaryKey: "MapName") as! String static let indexName = Bundle.main.object(forInfoDictionaryKey: "IndexName") as! String static let identityPoolId = Bundle.main.object(forInfoDictionaryKey: "IdentityPoolId") as! String static let trackerName = Bundle.main.object(forInfoDictionaryKey: "TrackerName") as! String }
使用 名稱建立新的資料夾,
ViewModel
並在其中新增TrackingViewModel.swift
檔案。import SwiftUI import AmazonLocationiOSAuthSDK import MapLibre final class TrackingViewModel : ObservableObject { @Published var trackingButtonText = NSLocalizedString("StartTrackingLabel", comment: "") @Published var trackingButtonColor = Color.blue @Published var trackingButtonIcon = "play.circle" @Published var region : String @Published var mapName : String @Published var indexName : String @Published var identityPoolId : String @Published var trackerName : String @Published var showAlert = false @Published var alertTitle = "" @Published var alertMessage = "" @Published var centerLabel = "" var clientIntialised: Bool var client: LocationTracker! var authHelper: AuthHelper var credentialsProvider: LocationCredentialsProvider? var mlnMapView: MLNMapView? var mapViewDelegate: MapViewDelegate? var lastGetTrackingTime: Date? var trackingActive: Bool init(region: String, mapName: String, indexName: String, identityPoolId: String, trackerName: String) { self.region = region self.mapName = mapName self.indexName = indexName self.identityPoolId = identityPoolId self.trackerName = trackerName self.authHelper = AuthHelper() self.trackingActive = false self.clientIntialised = false } func authWithCognito(identityPoolId: String?) { guard let identityPoolId = identityPoolId?.trimmingCharacters(in: .whitespacesAndNewlines) else { alertTitle = NSLocalizedString("Error", comment: "") alertMessage = NSLocalizedString("NotAllFieldsAreConfigured", comment: "") showAlert = true return } credentialsProvider = authHelper.authenticateWithCognitoUserPool(identityPoolId: identityPoolId) initializeClient() } func initializeClient() { client = LocationTracker(provider: credentialsProvider!, trackerName: trackerName) clientIntialised = true } }