iOS Swift位置管理器无法正确更新



我正在使用CLLocationManager获取用户位置。当用户移动时,我需要更新他们的位置。我正在使用此代码:

import UIKit
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate {
    private var locationManager = CLLocationManager()
    lazy var locations = [CLLocation]()
    var op:String = ""
    @IBOutlet weak var resultTxt: UITextView!
    @IBAction func Start(sender: AnyObject) {
        startLocationManager()
        showResult()
    }
    override func viewDidLoad() {
        super.viewDidLoad()
    }
    func startLocationManager(){
        locationManager.delegate = self
        locationManager.allowsBackgroundLocationUpdates = true
        locationManager.distanceFilter = kCLDistanceFilterNone
        locationManager.pausesLocationUpdatesAutomatically = false
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.requestWhenInUseAuthorization()
        locationManager.requestAlwaysAuthorization()
        locationManager.startUpdatingLocation()
    }
    func startLocationTracking() {
        NSLog("startLocationTracking")
        if CLLocationManager.locationServicesEnabled() {
            switch(CLLocationManager.authorizationStatus()) {
            case .NotDetermined, .Restricted, .Denied:
                print("No access")
                self.startLocationManager()
            case .AuthorizedAlways, .AuthorizedWhenInUse:
                NSLog("authorizationStatus authorized")
            }
        } else {
            print("Location services are not enabled")
            self.startLocationManager()
        }
    }
    func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        for location in locations {
            let howRecent = location.timestamp.timeIntervalSinceNow
            if abs(howRecent) < 10 && location.horizontalAccuracy < 20 {
                //update distance
                self.locations.append(location)
                showResult()
            }
        }
    }
    func showResult(){
        let currentDate = NSDate()
        let res:String = "Result LAT : (self.locations.last?.coordinate.latitude) AND LNG : (self.locations.last?.coordinate.longitude)  Time : (currentDate.toShortTimeString()) n "
        op += res
        self.resultTxt.text = op
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

我已经在.plist中添加了NSLocationAlwaysUsageDescriptionNSLocationWhenInUseUsageDescription。该代码首次工作正常。但是,当用户移动时," didUpdateLocations"不会被触发。有人可以帮我,我做错了什么?

尝试添加这些行,以便在用户移动时监视重大位置更改:

locationManager.startMonitoringSignificantLocationChanges()
locationManager.distanceFilter = 300 //value is up to you

最新更新