iOS后台模式位置更新 – 管理器不在后台模式下更新

我刚刚关注了http://www.raywenderlich.com/92428/background-modes-ios-swift-tutorial位置更新部分。

但经理不会在后台模式下打印位置信息。

然后当app进入前台时,经理打印日志到Xcode的控制台。

这段代码对吗?

import UIKit import CoreLocation @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, CLLocationManagerDelegate { var window: UIWindow? var manager = CLLocationManager() func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. manager.desiredAccuracy = kCLLocationAccuracyBest manager.delegate = self manager.requestAlwaysAuthorization() manager.startUpdatingLocation() return true } func locationManager(manager: CLLocationManager, didUpdateToLocation newLocation: CLLocation, fromLocation oldLocation: CLLocation) { if UIApplication.sharedApplication().applicationState != .Active { NSLog("App is backgrounded. New location is %@", newLocation) } } ..... } 

我自己得到了答案。

如果您的应用在iOS 9.0或更高版本上运行,并希望在后台运行您的位置服务应用,

你必须将allowsBackgroundLocationUpdates变量设置为true。

所以这是我的代码。

 import UIKit import CoreLocation @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, CLLocationManagerDelegate { var window: UIWindow? var manager = CLLocationManager() func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. manager.desiredAccuracy = kCLLocationAccuracyBest manager.delegate = self manager.requestAlwaysAuthorization() manager.startUpdatingLocation() if #available(iOS 9.0, *){ manager.allowsBackgroundLocationUpdates = true } return true } func locationManager(manager: CLLocationManager, didUpdateToLocation newLocation: CLLocation, fromLocation oldLocation: CLLocation) { if UIApplication.sharedApplication().applicationState != .Active { NSLog("App is backgrounded. New location is %@", newLocation) } } ..... }