Swift iOS:收到远程通知后,Closure不会在后台运行

我正在写一个iOS应用程序,要求在收到推送通知时更新设备的GPS位置。

我使用闭包来获取当前的GPS位置。 这个代码在应用程序处于前台时完美运行(“新的远程通知”和“获得位置”都被打印到控制台),但是当应用程序在后台时,只有“新的远程通知”(并且没有位置错误)被打印到控制台。 因此,我现在还没有设备的GPS位置,这对于我的应用程序的function非常重要。

任何帮助将不胜感激。 谢谢。

我在Info.plist文件中有'必需的背景模式';

App registers for location updates App downloads content from the network App downloads content in response to push notifications 

我的应用程序还可以随时访问位置,包括背景(在代码中的其他位置成功testing过):NSLocationAlwaysUsageDescription位于Info.plist文件中

在我的AppDelegate文件中:

  func application(application: UIApplication!, didReceiveRemoteNotification userInfo:NSDictionary!) { println("New remote notification") var notification:NSDictionary = userInfo as NSDictionary var loc: LocationManager? loc = LocationManager() loc!.fetchWithCompletion {location, error in // fetch location or an error if let myloc = location { var lat = myloc.coordinate.latitude as Double var lon = myloc.coordinate.longitude as Double println("Got location") } else if let err = error { println(err.localizedDescription) } loc = nil } } 

如果app不在前台,请确保使用beginBackgroundTaskWithExpirationHandler请求一点时间来完成请求,然后在完成时调用endBackgroundTask

有关更多信息,请参阅适用于iOS应用程序编程指南的后台执行章节中的执行有限长度任务

Interesting Posts