Création d'une application iOS - Amazon Location Service

Les traductions sont fournies par des outils de traduction automatique. En cas de conflit entre le contenu d'une traduction et celui de la version originale en anglais, la version anglaise prévaudra.

Création d'une application iOS

Dans cette section, vous allez créer une application iOS avec la possibilité de rechercher un emplacement et de suivre au premier plan. Tout d'abord, vous allez créer vos ressources Amazon Location et une identité Amazon Cognito pour votre application.

Création de ressources Amazon Location pour votre application

Si vous ne les avez pas déjà, vous devez créer les ressources Amazon Location que votre application utilisera. Vous allez créer une ressource cartographique pour afficher des cartes dans votre application, un index des lieux pour rechercher des emplacements sur la carte et un traceur pour suivre un objet sur la carte.

Pour ajouter des ressources de localisation à votre application
  1. Choisissez le style de carte que vous souhaitez utiliser.

    1. Dans la console Amazon Location, sur la page Cartes, choisissez Create map pour prévisualiser les styles de carte.

    2. Ajoutez un nom et une description pour la nouvelle ressource cartographique. Notez le nom que vous utilisez pour la ressource cartographique. Vous en aurez besoin lors de la création de votre fichier de script ultérieurement dans le didacticiel.

    3. Choisissez une carte.

      Note

      Le choix d'un style de carte permet également de choisir le fournisseur de données cartographiques que vous utiliserez. Si votre application suit ou achemine des actifs que vous utilisez dans votre entreprise, tels que des véhicules de livraison ou des employés, vous ne pouvez utiliser HERE que comme fournisseur de géolocalisation. Pour plus d'informations, consultez la section 82 des conditions de AWS service.

    4. Acceptez les conditions générales d'Amazon Location, puis choisissez Create map. Vous pouvez interagir avec la carte que vous avez choisie : zoomer, dézoomer ou vous déplacer dans n'importe quelle direction.

    5. Notez le nom de ressource Amazon (ARN) affiché pour votre nouvelle ressource cartographique. Vous l'utiliserez pour créer l'authentification correcte plus loin dans ce didacticiel.

  2. Choisissez l'index des lieux que vous souhaitez utiliser.

    1. Dans la console Amazon Location, sur la page des index de lieux, choisissez Create place index.

    2. Ajoutez un nom et une description pour la nouvelle ressource d'index des lieux. Notez le nom que vous utilisez pour la ressource d'index des lieux. Vous en aurez besoin lors de la création de votre fichier de script ultérieurement dans le didacticiel.

    3. Choisissez un fournisseur de données.

      Note

      Dans la plupart des cas, choisissez le fournisseur de données qui correspond au fournisseur de cartes que vous avez déjà choisi. Cela permet de garantir que les recherches correspondent aux cartes.

      Si votre application suit ou achemine des actifs que vous utilisez dans votre entreprise, tels que des véhicules de livraison ou des employés, vous ne pouvez utiliser HERE que comme fournisseur de géolocalisation. Pour plus d'informations, consultez la section 82 des conditions de AWS service.

    4. Choisissez l'option Stockage des données. Pour ce didacticiel, les résultats ne sont pas enregistrés. Vous pouvez donc choisir Non, à usage unique uniquement.

    5. Acceptez les conditions générales d'Amazon Location, puis choisissez Create place index.

    6. Notez l'ARN affiché pour votre nouvelle ressource d'index de localisation. Vous l'utiliserez pour créer l'authentification correcte dans la section suivante de ce didacticiel.

  3. Pour créer un outil de suivi à l'aide de la console Amazon Location.

    1. Ouvrez la console Amazon Location Service.

    2. Dans le volet de navigation de gauche, choisissez Trackers.

    3. Choisissez Créer un tracker.

    4. Remplissez tous les champs obligatoires.

    5. Sous Filtrage des positions, nous vous recommandons d'utiliser le paramètre par défaut : TimeBased.

    6. Choisissez Créer un tracker pour terminer.

Configuration de l'authentification pour votre application

L'application que vous créez dans ce didacticiel est utilisée de manière anonyme, ce qui signifie que vos utilisateurs ne sont pas tenus de se AWS connecter pour utiliser l'application. Cependant, les API Amazon Location Service nécessitent une authentification pour être utilisées. Vous utiliserez Amazon Cognito pour authentifier et autoriser les utilisateurs anonymes. Ce didacticiel utilisera Amazon Cognito pour authentifier votre application.

Note

Pour plus d'informations sur l'utilisation d'Amazon Cognito avec Amazon Location Service, consultez. Octroi de l'accès à Amazon Location Service

Les didacticiels suivants vous montrent comment configurer l'authentification pour la carte, l'index des lieux et le tracker que vous avez créés, ainsi que comment configurer les autorisations pour Amazon Location.

Création d'une politique IAM pour le suivi
  1. Connectez-vous à la console IAM à l'adresse https://console.aws.amazon.com/iam/ en tant qu'utilisateur disposant d'autorisations Administrateur.

  2. Dans le panneau de navigation, sélectionnez Policies (Politiques).

  3. Dans le panneau de contenu, sélectionnez Créer une politique.

  4. Choisissez l'option JSON, puis copiez et collez cette politique JSON dans la zone de texte JSON.

    { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "geo:GetMapTile", "geo:GetMapStyleDescriptor", "geo:GetMapSprites", "geo:GetMapGlyphs", "geo:SearchPlaceIndexForPosition", "geo:GetDevicePositionHistory", "geo:BatchUpdateDevicePosition" ], "Resource": [ "arn:aws:geo:{Region}:{Account}:map/{MapName}", "arn:aws:geo:{Region}:{Account}:place-index/{IndexName}", "arn:aws:geo:{Region}:{Account}:tracker/{TrackerName}" ] } ] }

    Il s'agit d'un exemple de politique pour le suivi. Pour utiliser cet exemple pour votre propre politique, remplacez les TrackerNameespaces réservés Region AccountIndexName,, MapName et.

    Note

    Bien que les pools d'identités non authentifiés soient destinés à être exposés sur des sites Internet non sécurisés, notez qu'ils seront échangés contre des informations d'identification standard limitées dans le temps. AWS

    Il est important de définir de manière appropriée les rôles IAM associés aux pools d'identités non authentifiés. Pour plus d'informations sur l'utilisation et la définition appropriée des politiques dans Amazon Cognito avec Amazon Location Service, consultez la section Accorder l'accès à Amazon Location Service.

  5. Sur la page Révision et création, saisissez un nom pour le champ de nom de la politique. Vérifiez les autorisations accordées par votre politique, puis choisissez Créer une politique pour enregistrer votre travail.

La nouvelle politique s'affiche dans la liste des politiques gérées et est prête à être attachée.

Configurez l'authentification pour votre suivi
  1. Configurez l'authentification pour votre application cartographique dans la console Amazon Cognito.

  2. Ouvrez la page Groupes d'identités.

    Note

    Le pool que vous créez doit se trouver dans le même AWS compte et dans la même AWS région que les ressources Amazon Location Service que vous avez créées dans la section précédente.

  3. Choisissez Create Identity Pool.

  4. En commençant par l'étape Configurer la confiance du pool d'identités. Pour l'authentification de l'accès utilisateur, sélectionnez Accès invité, puis appuyez sur Suivant.

  5. Sur la page Configurer les autorisations, sélectionnez Utiliser un rôle IAM existant et entrez le nom du rôle IAM que vous avez créé à l'étape précédente. Lorsque vous êtes prêt, appuyez sur Suivant pour passer à l'étape suivante.

  6. Sur la page Configurer les propriétés, attribuez un nom à votre pool d'identités. Appuyez ensuite sur Suivant.

  7. Sur la page Réviser et créer, passez en revue toutes les informations présentes, puis appuyez sur Créer un pool d'identités.

  8. Ouvrez la page Groupes d'identités et sélectionnez le pool d'identités que vous venez de créer. Copiez ou notez ensuite IdentityPoolId ce que vous utiliserez ultérieurement dans le script de votre navigateur.

Création de l'application iOS de base

Dans ce didacticiel, vous allez créer une application iOS qui intègre une carte et permet à l'utilisateur de trouver ce qui se trouve à un emplacement sur la carte.

Créons d'abord une application Swift à l'aide de l'assistant de projet de Xcode.

Pour créer une application vide (Xcode)
  1. Ouvrez Xcode, puis dans le menu, choisissez Fichier, Nouveau, Nouveau projet.

  2. Dans l'onglet iOS, sélectionnez App, puis Next.

  3. Entrez un nom de produit, un identifiant d'organisation et dans le champ de saisie de l'interfaceSwiftUI. Choisissez Next pour finaliser la sélection.

  4. Sélectionnez un emplacement où vous allez enregistrer votre projet et appuyez sur le bouton Créer pour créer l'application vide.

Une fois que vous avez créé l'application de base, vous devez installer les packages requis pour l'exemple d'application.

Installation des dépendances requises
  1. Dans Xcode, cliquez avec le bouton droit sur le projet et choisissez Ajouter des packages... . Cela ouvrira la fenêtre Packages, dans laquelle vous pourrez ajouter des packages à votre projet.

  2. Dans la fenêtre Packages, ajoutez les packages suivants :

Configuration du code initial

Activez les autorisations de localisation dans votre application
  1. Ouvrez votre projet Xcode.

  2. Localisez le Info.plist fichier du projet.

  3. Ajoutez les clés nécessaires pour les autorisations de localisation en fonction des exigences de votre application. Voici les clés :

    • NSLocationWhenInUseUsageDescription: description des raisons pour lesquelles votre application a besoin d'un accès à la localisation lorsqu'elle est utilisée.

    • NSLocationAlwaysAndWhenInUseUsageDescription: description des raisons pour lesquelles votre application a besoin d'un accès permanent à la localisation.

Vous devez maintenant configurer les valeurs des ressources dans votre application. Ajoutez un nouveau fichier nommé Config.xcconfig et renseignez les valeurs que vous avez créées précédemment dans la console Amazon.

REGION = INDEX_NAME = MAP_NAME = IDENTITY_POOL_ID = TRACKER_NAME =
  1. Dans la section du navigateur de gauche, sélectionnez le projet.

  2. Dans la section des cibles, sélectionnez votre application et cliquez sur l'onglet Info.

  3. Ajoutez des propriétés d'information avec des valeurs comme celles ci-dessous :

  4. Ajoutez le Config.swift fichier avec le contenu ci-dessous, qui lira les valeurs de configuration à partir du fichier d'informations du bundle.

    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 }
  5. Créez un nouveau dossier portant ce nom ViewModel et ajoutez-y un TrackingViewModel.swift fichier.

    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 } }

Ajouter une carte interactive à votre application

Vous allez maintenant ajouter le contrôle cartographique à votre application. Ce didacticiel utilise MapLibre l' AWS API pour gérer la vue cartographique dans l'application. Le contrôle cartographique lui-même fait partie de la bibliothèque MapLibre GL Native iOS.

  1. Ajoutez MapView.swift le fichier dans le dossier Views avec le code suivant :

    import SwiftUI import MapLibre struct MapView: UIViewRepresentable { var onMapViewAvailable: ((MLNMapView) -> Void)? var mlnMapView: MLNMapView? var trackingViewModel: TrackingViewModel func makeCoordinator() -> MapView.Coordinator { return Coordinator(self, trackingViewModel: trackingViewModel) } func makeUIView(context: Context) -> MLNMapView { let styleURL = URL(string: "https://maps.geo.\(trackingViewModel.region).amazonaws.com/maps/v0/maps/\(trackingViewModel.mapName)/style-descriptor") let mapView = MLNMapView(frame: .zero, styleURL: styleURL) mapView.autoresizingMask = [.flexibleWidth, .flexibleHeight] mapView.setZoomLevel(15, animated: true) mapView.showsUserLocation = true mapView.userTrackingMode = .follow context.coordinator.mlnMapView = mapView mapView.delegate = context.coordinator mapView.logoView.isHidden = true context.coordinator.addCenterMarker() onMapViewAvailable?(mapView) trackingViewModel.mlnMapView = mapView return mapView } func updateUIView(_ uiView: MLNMapView, context: Context) { } class Coordinator: NSObject, MLNMapViewDelegate, MapViewDelegate { var control: MapView var mlnMapView: MLNMapView? var trackingViewModel: TrackingViewModel var centerMarker: MLNPointAnnotation? public init(_ control: MapView, trackingViewModel: TrackingViewModel) { self.control = control self.trackingViewModel = trackingViewModel super.init() self.trackingViewModel.mapViewDelegate = self } func mapViewDidFinishRenderingMap(_ mapView: MLNMapView, fullyRendered: Bool) { if(fullyRendered) { mapView.accessibilityIdentifier = "MapView" mapView.isAccessibilityElement = false } } func addCenterMarker() { guard let mlnMapView = mlnMapView else { return } let centerCoordinate = mlnMapView.centerCoordinate let marker = MLNPointAnnotation() marker.coordinate = centerCoordinate marker.accessibilityLabel = "CenterMarker" mlnMapView.addAnnotation(marker) centerMarker = marker trackingViewModel.reverseGeocodeCenter(centerCoordinate: centerCoordinate, marker: marker) } func mapView(_ mapView: MLNMapView, regionDidChangeAnimated animated: Bool) { if let marker = centerMarker { DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) { mapView.deselectAnnotation(marker, animated: false) marker.coordinate = mapView.centerCoordinate let centerCoordinate = mapView.centerCoordinate self.trackingViewModel.reverseGeocodeCenter(centerCoordinate: centerCoordinate, marker: marker) } } } } }
  2. Ajoutez AWSSignatureV4Delegate le fichier sous le ViewModeldossier. Ce fichier est utilisé pour signer toutes les requêtes MapView http pour afficher la carte :

    import MapLibre import AmazonLocationiOSAuthSDK class AWSSignatureV4Delegate : NSObject, MLNOfflineStorageDelegate { private let awsSigner: AWSSigner init(credentialsProvider: LocationCredentialsProvider) { self.awsSigner = DENY LIST ERROR , serviceName: "geo") super.init() } func offlineStorage(_ storage: MLNOfflineStorage, urlForResourceOf kind: MLNResourceKind, with url: URL) -> URL { if url.host?.contains("amazonaws.com") != true { return url } let signedURL = awsSigner.signURL(url: url, expires: .hours(1)) return signedURL } }
  3. Ajoutez UserLocationView.swift le fichier dans le dossier Views. Cela ajoute un bouton qui centre la carte sur l'emplacement de l'utilisateur

    import SwiftUI struct UserLocationView: View { @ObservedObject var trackingViewModel: TrackingViewModel var body: some View { Button(action: { trackingViewModel.locateMe() }) { Image(systemName: "scope") .resizable() .frame(width: 24, height: 24) .padding(5) .background(Color.white) .foregroundColor(.blue) .clipShape(RoundedRectangle(cornerRadius: 8)) .shadow(color: Color.black.opacity(0.3), radius: 3, x: 0, y: 2) } .accessibility(identifier: "LocateMeButton") .padding(.trailing, 10) .padding(.bottom, 10) .frame(maxWidth: .infinity, alignment: .trailing) } }
  4. Ajoutez le TrackingView.swift fichier avec le code suivant :

    import SwiftUI struct TrackingView: View { @ObservedObject var trackingViewModel: TrackingViewModel var body: some View { ZStack(alignment: .bottom) { MapView(trackingViewModel: trackingViewModel) VStack { UserLocationView(trackingViewModel: trackingViewModel) } } .onAppear() { if !trackingViewModel.identityPoolId.isEmpty { trackingViewModel.authWithCognito(identityPoolId: trackingViewModel.identityPoolId) } } } }

Vous pouvez maintenant créer l'application. Pour l'exécuter, vous devrez peut-être configurer un appareil pour l'émuler dans Xcode ou utiliser l'application sur votre appareil. Utilisez cette application pour voir comment se comporte le contrôle cartographique. Vous pouvez vous déplacer en faisant glisser le pointeur sur la carte et en pinçant pour zoomer. Vous pouvez vous-même modifier le mode de fonctionnement du contrôle cartographique pour le personnaliser en fonction des besoins de votre application.

Vous allez maintenant ajouter la recherche par géocodage inversé à l'application, où vous trouverez les éléments à un emplacement donné. Pour simplifier l'utilisation d'une application iOS, nous allons effectuer une recherche au centre de l'écran. Pour trouver un nouvel emplacement, déplacez la carte jusqu'à l'endroit où vous souhaitez effectuer la recherche. Nous placerons un marqueur au centre de la carte pour indiquer où nous cherchons.

  1. Ajoutez le code suivant dans le fichier « TrackingViewModel .swift` qui est lié à la recherche par géocodage inversé

    func reverseGeocodeCenter(centerCoordinate: CLLocationCoordinate2D, marker: MLNPointAnnotation) { let position = [NSNumber(value: centerCoordinate.longitude), NSNumber(value: centerCoordinate.latitude)] searchPositionAPI(position: position, marker: marker) } func searchPositionAPI(position: [Double], marker: MLNPointAnnotation) { if let amazonClient = authHelper.getLocationClient() { Task { let searchRequest = SearchPlaceIndexForPositionInput(indexName: indexName, language: "en" , maxResults: 10, position: position) let searchResponse = try? await amazonClient.searchPosition(indexName: indexName, input: searchRequest) DispatchQueue.main.async { self.centerLabel = searchResponse?.results?.first?.place?.label ?? "" self.mlnMapView?.selectAnnotation(marker, animated: true, completionHandler: {}) } } } }
  2. Mettez à jour le TrackingView.swift fichier avec le code suivant qui affichera l'adresse de l'emplacement centré de la vue cartographique

    import SwiftUI struct TrackingView: View { @ObservedObject var trackingViewModel: TrackingViewModel var body: some View { ZStack(alignment: .bottom) { if trackingViewModel.mapSigningIntialised { MapView(trackingViewModel: trackingViewModel) VStack { UserLocationView(trackingViewModel: trackingViewModel) CenterAddressView(trackingViewModel: trackingViewModel) } } else { Text("Loading...") } } .onAppear() { if !trackingViewModel.identityPoolId.isEmpty { Task { do { try await trackingViewModel.authWithCognito(identityPoolId: trackingViewModel.identityPoolId) } catch { print(error) } } } } } }

Ajouter le suivi à votre application

La dernière étape de votre application consiste à ajouter une fonctionnalité de suivi à votre application. Dans ce cas, vous allez ajouter le suivi de départ, arrêter le suivi, récupérer et afficher les points de suivi sur votre application.

  1. Ajoutez le TrackingBottomView.swift fichier dans votre projet. Il comporte un bouton qui démarre et arrête le suivi de la position des utilisateurs et affiche les points de suivi sur la carte.

    import SwiftUI struct TrackingBottomView: View { @ObservedObject var trackingViewModel: TrackingViewModel var body: some View { Button(action: { Task { if(trackingViewModel.trackingButtonText == NSLocalizedString("StartTrackingLabel", comment: "")) { trackingViewModel.startTracking() } else { trackingViewModel.stopTracking() } } }) { HStack { Spacer() Text("Tracking") .foregroundColor(trackingViewModel.trackingButtonColor) .background(.white) .cornerRadius(15.0) Image(systemName: trackingViewModel.trackingButtonIcon) .resizable() .frame(width: 24, height: 24) .padding(5) .background(.white) .foregroundColor(trackingViewModel.trackingButtonColor) } } .accessibility(identifier: "TrackingButton") .background(.white) .clipShape(RoundedRectangle(cornerRadius: 8)) .padding(.trailing, 10) .padding(.bottom, 40) .frame(width: 130, alignment: .trailing) .shadow(color: Color.black.opacity(0.3), radius: 3, x: 0, y: 2) } }
  2. Mettre à jour le TrackingView.swift fichier avec le code suivant

    import SwiftUI struct TrackingView: View { @ObservedObject var trackingViewModel: TrackingViewModel var body: some View { ZStack(alignment: .bottom) { if trackingViewModel.mapSigningIntialised { MapView(trackingViewModel: trackingViewModel) VStack { UserLocationView(trackingViewModel: trackingViewModel) CenterAddressView(trackingViewModel: trackingViewModel) TrackingBottomView(trackingViewModel: trackingViewModel) } } else { Text("Loading...") } } .onAppear() { if !trackingViewModel.identityPoolId.isEmpty { Task { do { try await trackingViewModel.authWithCognito(identityPoolId: trackingViewModel.identityPoolId) } catch { print(error) } } } } } }
  3. Ajoutez le code suivant dans TrackingViewModel.swift le fichier. Ces fonctions sont responsables du suivi des démarrages et des arrêts. Il affichera également une alerte d'erreur si l'autorisation de localisation de l'utilisateur est refusée.

  4. Pour implémenter le suivi au premier plan, copiez-collez l'exemple de code suivant :

    func showLocationDeniedRationale() { alertTitle = NSLocalizedString("locationManagerAlertTitle", comment: "") alertMessage = NSLocalizedString("locationManagerAlertText", comment: "") showAlert = true } // Required in info.plist: Privacy - Location When In Use Usage Description func startTracking() { do { print("Tracking Started...") if(client == nil) { initializeClient() } try client.startTracking() DispatchQueue.main.async { [self] in self.trackingButtonText = NSLocalizedString("StopTrackingLabel", comment: "") self.trackingButtonColor = .red self.trackingButtonIcon = "pause.circle" trackingActive = true } } catch TrackingLocationError.permissionDenied { showLocationDeniedRationale() } catch { print("error in tracking") } } func stopTracking() { print("Tracking Stopped...") client.stopTracking() trackingButtonText = NSLocalizedString("StartTrackingLabel", comment: "") trackingButtonColor = .blue trackingButtonIcon = "play.circle" trackingActive = false }
    Note

    Ils startTracking demanderont l'autorisation de localisation de l'utilisateur. L'application doit utiliser les autorisations When In Use ou Only Once. Dans le cas contraire, l'application affichera une erreur de refus d'autorisation.

Pour obtenir et afficher les emplacements de suivi, suivez cette procédure :

  1. Pour obtenir les emplacements depuis l'appareil de l'utilisateur, vous devez fournir la date et l'heure de début et de fin. Un seul appel renvoie un maximum de 100 emplacements de suivi, mais s'il y en a plus de 100, il renverra une valeur `NextToken`. Vous devrez appeler les appels getTrackerDevice `Location` suivants avec `NextToken` pour charger plus de points de suivi pour les heures de début et de fin données.

    func getTrackingPoints(nextToken: String? = nil) async throws { guard trackingActive else { return } // Initialize startTime to 24 hours ago from the current date and time. let startTime: Date = Date().addingTimeInterval(-86400) var endTime: Date = Date() if lastGetTrackingTime != nil { endTime = lastGetTrackingTime! } let result = try await client?.getTrackerDeviceLocation(nextToken: nextToken, startTime: startTime, endTime: endTime) if let trackingData = result { lastGetTrackingTime = Date() let devicePositions = trackingData.devicePositions let positions = devicePositions!.sorted { (pos1: LocationClientTypes.DevicePosition, pos2: LocationClientTypes.DevicePosition) -> Bool in guard let date1 = pos1.sampleTime, let date2 = pos2.sampleTime else { return false } return date1 < date2 } let trackingPoints = positions.compactMap { position -> CLLocationCoordinate2D? in guard let latitude = position.position!.last, let longitude = position.position!.first else { return nil } return CLLocationCoordinate2D(latitude: latitude, longitude: longitude) } DispatchQueue.main.async { self.mapViewDelegate!.drawTrackingPoints( trackingPoints: trackingPoints) } if let nextToken = trackingData.nextToken { try await getTrackingPoints(nextToken: nextToken) } } }
  2. Remplacez maintenant le code du MapView.swift fichier par le code suivant :

    import SwiftUI import MapLibre struct MapView: UIViewRepresentable { var onMapViewAvailable: ((MLNMapView) -> Void)? var mlnMapView: MLNMapView? var trackingViewModel: TrackingViewModel func makeCoordinator() -> MapView.Coordinator { return Coordinator(self, trackingViewModel: trackingViewModel) } func makeUIView(context: Context) -> MLNMapView { let styleURL = URL(string: "https://maps.geo.\(trackingViewModel.region).amazonaws.com/maps/v0/maps/\(trackingViewModel.mapName)/style-descriptor") let mapView = MLNMapView(frame: .zero, styleURL: styleURL) mapView.autoresizingMask = [.flexibleWidth, .flexibleHeight] mapView.setZoomLevel(15, animated: true) mapView.showsUserLocation = true mapView.userTrackingMode = .follow context.coordinator.mlnMapView = mapView mapView.delegate = context.coordinator mapView.logoView.isHidden = true context.coordinator.addCenterMarker() onMapViewAvailable?(mapView) trackingViewModel.mlnMapView = mapView return mapView } func updateUIView(_ uiView: MLNMapView, context: Context) { } class Coordinator: NSObject, MLNMapViewDelegate, MapViewDelegate { var control: MapView var mlnMapView: MLNMapView? var trackingViewModel: TrackingViewModel var centerMarker: MLNPointAnnotation? public init(_ control: MapView, trackingViewModel: TrackingViewModel) { self.control = control self.trackingViewModel = trackingViewModel super.init() self.trackingViewModel.mapViewDelegate = self } func mapViewDidFinishRenderingMap(_ mapView: MLNMapView, fullyRendered: Bool) { if(fullyRendered) { mapView.accessibilityIdentifier = "MapView" mapView.isAccessibilityElement = false } } func addCenterMarker() { guard let mlnMapView = mlnMapView else { return } let centerCoordinate = mlnMapView.centerCoordinate let marker = MLNPointAnnotation() marker.coordinate = centerCoordinate marker.accessibilityLabel = "CenterMarker" mlnMapView.addAnnotation(marker) centerMarker = marker trackingViewModel.reverseGeocodeCenter(centerCoordinate: centerCoordinate, marker: marker) } func mapView(_ mapView: MLNMapView, regionDidChangeAnimated animated: Bool) { if let marker = centerMarker { DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) { mapView.deselectAnnotation(marker, animated: false) marker.coordinate = mapView.centerCoordinate let centerCoordinate = mapView.centerCoordinate self.trackingViewModel.reverseGeocodeCenter(centerCoordinate: centerCoordinate, marker: marker) } } } func mapView(_ mapView: MLNMapView, viewFor annotation: MLNAnnotation) -> MLNAnnotationView? { guard let pointAnnotation = annotation as? MLNPointAnnotation else { return nil } let reuseIdentifier: String var color: UIColor = .black if pointAnnotation.accessibilityLabel == "Tracking" { reuseIdentifier = "TrackingAnnotation" color = UIColor(red: 0.00784313725, green: 0.50588235294, blue: 0.58039215686, alpha: 1) } else if pointAnnotation.accessibilityLabel == "LocationChange" { reuseIdentifier = "LocationChange" color = .gray } else { reuseIdentifier = "DefaultAnnotationView" } var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseIdentifier) if annotationView == nil { if reuseIdentifier != "DefaultAnnotationView" { annotationView = MLNAnnotationView(annotation: annotation, reuseIdentifier: reuseIdentifier) //If point annotation is an uploaded Tracking point the radius is 20 and color is blue, otherwise radius is 10 and color is gray let radius = pointAnnotation.accessibilityLabel == "Tracking" ? 20:10 annotationView?.frame = CGRect(x: 0, y: 0, width: radius, height: radius) annotationView?.backgroundColor = color annotationView?.layer.cornerRadius = 10 if pointAnnotation.accessibilityLabel == "Tracking" { annotationView?.layer.borderColor = UIColor.white.cgColor annotationView?.layer.borderWidth = 2.0 annotationView?.layer.shadowColor = UIColor.black.cgColor annotationView?.layer.shadowOffset = CGSize(width: 0, height: 2) annotationView?.layer.shadowRadius = 3 annotationView?.layer.shadowOpacity = 0.2 annotationView?.clipsToBounds = false } } else { return nil } } return annotationView } func mapView(_ mapView: MLNMapView, didUpdate userLocation: MLNUserLocation?) { if (userLocation?.location) != nil { if trackingViewModel.trackingActive { let point = MLNPointAnnotation() point.coordinate = (userLocation?.location!.coordinate)! point.accessibilityLabel = "LocationChange" mapView.addAnnotation(point) Task { do { try await trackingViewModel.getTrackingPoints() } catch { print(error) } } } } } func checkIfTrackingAnnotationExists(on mapView: MLNMapView, at coordinates: CLLocationCoordinate2D) -> Bool { let existingAnnotation = mapView.annotations?.first(where: { annotation in guard let annotation = annotation as? MLNPointAnnotation else { return false } return annotation.coordinate.latitude == coordinates.latitude && annotation.coordinate.longitude == coordinates.longitude && annotation.accessibilityLabel == "Tracking" }) return existingAnnotation != nil } public func drawTrackingPoints(trackingPoints: [CLLocationCoordinate2D]?) { guard let mapView = mlnMapView, let newTrackingPoints = trackingPoints, !newTrackingPoints.isEmpty else { return } let uniqueCoordinates = newTrackingPoints.filter { coordinate in !checkIfTrackingAnnotationExists(on: mapView, at: coordinate) } let points = uniqueCoordinates.map { coordinate -> MLNPointAnnotation in let point = MLNPointAnnotation() point.coordinate = coordinate point.accessibilityLabel = "Tracking" return point } mapView.addAnnotations(points) } } } protocol MapViewDelegate: AnyObject { func drawTrackingPoints(trackingPoints: [CLLocationCoordinate2D]?) }

Pour localiser des valeurs de chaîne, procédez comme suit.

  1. Créez et ajoutez un nouveau fichier appeléLocalizable.xcstrings.

  2. Cliquez avec le bouton droit sur le Localizable.xcstrings fichier et ouvrez-le en tant que code source.

  3. Remplacez son contenu par le suivant :

    { "sourceLanguage" : "en", "strings" : { "Cancel" : { "extractionState" : "manual", "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "Cancel" } } } }, "Error" : { "extractionState" : "manual", "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "Error" } } } }, "Loading..." : { }, "locationManagerAlertText" : { "extractionState" : "manual", "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "Allow \\\"Quick Start App\\\" to use your location" } } } }, "locationManagerAlertTitle" : { "extractionState" : "manual", "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "We need your location to detect your location in map" } } } }, "NotAllFieldsAreConfigured" : { "extractionState" : "manual", "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "Not all the fields are configured" } } } }, "OK" : { "extractionState" : "manual", "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "OK" } } } }, "StartTrackingLabel" : { "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "Start Tracking" } } } }, "StopTrackingLabel" : { "localizations" : { "en" : { "stringUnit" : { "state" : "translated", "value" : "Stop Tracking" } } } }, "Tracking" : { } }, "version" : "1.0" }
  4. Enregistrez vos fichiers, puis créez et exécutez votre application pour prévisualiser les fonctionnalités.

  5. Autorisez l'autorisation de localisation et appuyez sur le bouton de suivi. L'application commencera à télécharger les positions des utilisateurs et à les télécharger sur l'Amazon Location Tracker. Il affichera également les changements de localisation des utilisateurs, les points de suivi et l'adresse actuelle sur la carte.

Votre demande de démarrage rapide est terminée. Ce didacticiel vous explique comment créer une application iOS qui :

  • Crée une carte avec laquelle les utilisateurs peuvent interagir.

  • Gère plusieurs événements cartographiques associés à la modification de la vue cartographique par l'utilisateur.

  • Appelle une API Amazon Location Service, spécifiquement pour effectuer une recherche sur la carte à un emplacement, à l'aide de l' searchByPosition API d'Amazon Location.

Quelle est la prochaine étape

Le code source de cette application est disponible sur GitHub.

Pour tirer le meilleur parti d'Amazon Location, vous pouvez consulter les ressources suivantes :