簡體   English   中英

如何在 iOS 的后台跟蹤用戶步行並使用 Swift 和 Xcode 計算到目前為止行進的距離?

[英]How do I track in the background in iOS a user walking and calculate the distance traveled so far using Swift and Xcode?

我如何在 iOS 的后台跟蹤用戶在 Apple MapKit 或 Google Maps Platform for iOS 中行走並使用 Swift 和 Xcode 計算到目前為止行進的距離?

我試過使用 MapKit。 我遇到的問題是,當 iOS 設備被鎖定時,核心位置停止跟蹤設備。 當設備解鎖,應用程序進入前台時,Core Location 再次開始跟蹤,從最后一個跟蹤點到應用程序進入前台時跟蹤的點繪制一條直線,從而跳過設備鎖定的所有時間. 如果谷歌地圖平台在這方面效果更好,我願意使用它。

以下是相關代碼:

override func viewDidLoad() {
    super.viewDidLoad()

    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.distanceFilter = kCLDistanceFilterNone
    locationManager.allowsBackgroundLocationUpdates = true
    if #available(iOS 11.0, *) {
        locationManager.showsBackgroundLocationIndicator = true
    }

    let status = CLLocationManager.authorizationStatus()

    if status == .authorizedAlways || status == .authorizedWhenInUse || status == .restricted {

        locationManager.startUpdatingLocation()
        locationManager.startMonitoringSignificantLocationChanges()

    } else {

        locationManager.requestAlwaysAuthorization()

    }

}

func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {

    if status == .authorizedAlways || status == .authorizedWhenInUse || status == .restricted {

        locationManager.startUpdatingLocation()
        locationManager.startMonitoringSignificantLocationChanges()

    } else {

        locationManager.requestAlwaysAuthorization()

    }

}

您是否在 .plist 中添加了Privacy - Location Always and When In Use Usage DescriptionPrivacy - Location When In Use Usage Description

然后,由於您可能在didUpdateLocations方法中符合CLLocationManagerDelegate ,您應該能夠執行您的代碼。

我的錯誤是我使用地圖中的用戶位置而不是傳遞給 didUpdateLocations 方法的用戶位置創建了線條。 地圖上的 userLocation 屬性不會在后台更新,而 CLLocationManager 的 userLocation 屬性會在后台更新。

這是更正后的代碼,在我更正的行上有注釋:

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

    print("didUpdateLocations", locations)

    if let userLocation = locations.first, polyline != nil {

        let userLocationMapPoint = MKMapPoint(userLocation.coordinate)
        let lastUserLocationMapPoint = MKMapPoint(route.last!)

        totalDistance += userLocationMapPoint.distance(to: lastUserLocationMapPoint)

        mapView.removeOverlay(polyline)

        route.append(userLocation.coordinate) // changed from route.append(mapView.userLocation.coordinate)

        polyline = MKPolyline(coordinates: route, count: route.count)

        mapView.addOverlay(polyline)

    }

    print("latitude:", mapView.userLocation.coordinate.latitude, "longitude:", mapView.userLocation.coordinate.longitude)

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM