如何通过推送通知触发后台捕获iOS位置?

时间:2016-09-23 21:21:50

标签: ios iphone swift core-location

每当我的应用收到推送通知时,即使屏幕关闭或应用在后台运行,我也想捕获iOS用户的位置。重要的是,该位置必须具有高精度,并在发送通知时立即捕获。 (然后我想将该位置发回服务器,应用程序仍然在后台。)

这可以在iOS中实现吗?我是该平台的新手,并且看到了很多令人困惑的信息,表明至少部分是可能的,但我不确定是否整个事情都是。我也找到了一些资源(例如这个问题iOS App Background Location (Push Notifications)),但它来自四年前,我知道最近的iOS版本发生了很多变化。

1 个答案:

答案 0 :(得分:0)

是的,这是可能的:在你的AppDelegate didFinishLaunchingWithOptions中, 检查是否从通知启动(在后台接收到APN),然后启动位置服务。什么时候 您收到一个位置,将其发送到后端,然后关闭位置服务。请记住 一般来说,在系统返回一个位置之前会有一些延迟,但这应该是可行的 应用程序再次休眠之前的时间量。有一些方法可以获得额外的背景知识 处理时间,如果需要。

// untested code, ignores all of the boilerplate Location Services Authorization code and request user permission to Location services
var locationManager: CLLocationManager?

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // Check if launched from notification (received APN while in background)
    if let notification = launchOptions?[UIApplicationLaunchOptionsKey.remoteNotification] as? [String: AnyObject] {
        let aps = notification["aps"] as! [String: AnyObject]
        print("received background apn, aps: \(aps)")

        locationManager = CLLocationManager()
        locationManager!.delegate = self
        locationManager!.startUpdatingLocation()    // this is what starts the location services query
    }

    ...

    return true
}


func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    let location = locations[0]

    // here is where you would send location to your backend

    // shut down location services:
    locationManager?.stopUpdatingLocation()
    locationManager?.delegate = nil
    locationManager = nil
}
相关问题