我创建了一个应用程序,即使应用程序在后台或屏幕已锁定,也会跟踪用户的位置。我已经在iOS 5的iPhone 5s设备上进行了测试,一切正常。更新到iOS 9.3.1后,我注意到应用程序将在后台运行大约10分钟,然后应用程序将自动停止。我昨天将手机更新到iOS 9.3.2,希望能解决这个问题。但问题仍然存在。
我在AppDelegate类中有以下代码
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
private static var backgroundService : BackgroundService? = nil
var startServices : Bool = false
public static var bgTask = UIBackgroundTaskIdentifier()
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
print("didFinishLaunchingWithOptions")
AppDelegate.bgTask = beginBackgroundUpdateTask()
startBackgroundService()
return true
}
internal func startBackgroundService(){
if AppDelegate.backgroundService == nil{
AppDelegate.backgroundService = BackgroundService.getBackgroundService()
}
AppDelegate.backgroundService!.startService(self)
}
internal func stopBackgroundService(){
AppDelegate.backgroundService!.stopService()
}
func beginBackgroundUpdateTask() -> UIBackgroundTaskIdentifier {
return UIApplication.sharedApplication().beginBackgroundTaskWithExpirationHandler({})
}
func applicationDidEnterBackground(application: UIApplication) {
self.startBackgroundService()
print("applicationDidEnterBackground")
}
}
已在iphone上为应用启用后台应用刷新和位置服务。已启用后台模式,并在Info.plist中添加了其他必需的权限。
问题不是由于我在iOS 9.2的另一部手机上测试代码而导致代码更改,而且运行正常。将第二部手机更新到iOS 9.3.2后,出现了同样的问题。 9.3中是否有任何变化导致此问题?我浏览了更改日志和文档,但没有找到任何有用的东西。有没有其他人遇到过类似的问题?我是否需要进行任何更改以确保该应用程序适用于iOS 9.3?
答案 0 :(得分:2)
终于设法解决了这个问题。按照建议添加locationManager.allowsBackgroundLocationUpdates = true
后问题仍然存在。虽然它在后台运行的时间较长但在某一点之后,应用程序停止获取位置数据。
在网上搜索了一下后,我遇到了这个设置
locationManager.pausesLocationUpdatesAutomatically = false
添加此行解决了问题,并且位置提取在后台运行而不会突然停止。它的默认值为true。
如@Ahmed和@Chajmz所述,iOS 9及更高版本中需要allowBackgroundLocationUpdates
在iOS 9及更高版本中,无论部署目标如何,您还必须将位置管理器对象的allowsBackgroundLocationUpdates属性设置为YES,以便接收后台位置更新。默认情况下,此属性为NO,并且应该保持这种状态,直到您的应用主动要求更新后台位置为止。
根据 CLLocationManager - pausesLocationUpdatesAutomatically
的文档允许位置管理器暂停更新可以延长目标设备的电池寿命,而不会牺牲位置数据。当此属性设置为true时,位置管理器会在位置数据不太可能更改时暂停更新(并关闭相应的硬件)。例如,如果用户在使用导航应用程序时停止食物,则位置管理器可能暂停更新一段时间。
此属性的默认值为true。
答案 1 :(得分:0)
从iOS 9开始,您可以避免使用backgroundTaskWithExpirationHandler
,如果您想要LocationManager
allowsBackgroundLocationUpdates
持续访问您的数据,可以使用LocationManager
但是,如果您停止if #available(iOS 9.0, *) {
manager.allowsBackgroundLocationUpdates = true
} else {
// Fallback on earlier versions
}
1}}在后台,您将无法从后台重新启动它。
tableView.allowsMultipleSelectionDuringEditing = true