簡體   English   中英

如何在推送通知觸發的情況下在后台捕獲iOS位置?

[英]How do I capture iOS location in the background, triggered by a push notification?

我希望每次我的應用收到推送通知時都捕獲iOS用戶的位置,即使屏幕關閉或應用在后台運行。 重要的是,該位置必須高度准確,並在發送通知時立即捕獲。 (然后,我想將該位置發布回服務器,而應用仍在后台。)

這可以在iOS中完成嗎? 我是該平台的新手,並且看到了很多令人困惑的信息,這些信息表明至少有一部分是可能的,但是我不確定是否全部。 我還找到了一些資源(例如,有關iOS應用程序背景位置(推送通知)的問題 ),但這是四年前的,我知道最近的iOS版本已經發生了很多變化。

是的,這是可能的:在您的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
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM