应用在后台时获取背景位置

时间:2015-12-14 16:51:06

标签: ios swift maps core-location

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

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'

任何想法如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

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