当应用程序处于后台时获取后台位置

Getting background locations when app is in background

这是我获取位置更新的简单当前代码:

class ViewController: UIViewController, CLLocationManagerDelegate {

     var locationManager: CLLocationManager!

    override func viewDidLoad() {
        super.viewDidLoad()

        locationManager = CLLocationManager()
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest

        locationManager.requestAlwaysAuthorization()

        locationManager.startUpdatingLocation()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func locationManager(manager: CLLocationManager, didUpdateToLocation newLocation: CLLocation, fromLocation oldLocation: CLLocation) {

        print("in here")
        if UIApplication.sharedApplication().applicationState == .Active {
            print("App in Foreground")

        } else {

            let Device = UIDevice.currentDevice()
            let iosVersion = Double(Device.systemVersion) ?? 0

            let iOS9 = iosVersion >= 9
            if iOS9{
                // This part gives me error which i think is needed to allow background updates in ios9?
                //locationManager.allowsBackgroundLocationUpdates = YES;
                //locationManager.pausesLocationUpdatesAutomatically = NO;
            }
            //let iOS7 = iosVersion >= 7 && iosVersion < 8
            print("App is backgrounded. New location is %@", newLocation)
        }
    }


}

我已将 NSLocationAlwaysUsageDescription 添加到我的 plist 文件中,因此可以在应用程序中更新后台位置,所以不用担心。

当 运行 在模拟器中用于前景和背景时,此代码工作正常。然后我想在我的设备上尝试它,一旦我将应用程序设置为后台,它就不会更新任何位置。我在几个地方读到,对于 iOS 9 你需要添加这段代码:

locationManager.allowsBackgroundLocationUpdates = YES;

我试图将其放入 swift 中的代码中,但我收到此错误消息:

Cannot assign value of type 'ObjCBool' to type 'Bool'

有什么解决办法吗?

您正在使用 Objective-C 布尔文字 YES,它作为 ObjCBool 类型导入 Swift。只需切换到使用 Swift 布尔文字 true 就可以了。