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

标签 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;

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

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

有什么解决办法吗?

最佳答案

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

关于ios - 当应用程序处于后台时获取后台位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34272421/

相关文章:

ios - 如何快速信任端点 iOS swift

swift - UITableViewCell 的文本字段结束编辑未调用

r - 在 R 中绘制 1990 年前的世界地图

c++ - 如何遍历多个 map 并获取其值? -C++

ios - 为什么我的代码没有进入下一个 View

iphone - 为什么 Instruments 在此代码中报告内存泄漏?

javascript - 使用 jQuery 将 <body> 位置设置为固定时避免恢复到页面顶部

swift - 带有枚举列表的 RealmSwift

ios - 链接多个静态库时出现重复符号错误。

GPS 转换 - 像素坐标到 GPS 坐标