ios - 获取位置后如何进行后台网络调用?

标签 ios swift swift3 locationmanager

当在后台更改位置时,我想将位置更新到服务器。每次收到重大位置更改时,我都希望有一种安全的方式在后台更新位置。如何调用网络电话?

 func endBackgroundUpdateTask() {
        UIApplication.shared.endBackgroundTask(self.backgroundUpdateTask)
        self.backgroundUpdateTask = UIBackgroundTaskInvalid
    }


    func scheduledLocationManager(_ manager: APScheduledLocationManager, didUpdateLocations locations: [CLLocation]) {
        print(locations.last?.description ?? "no location")
        self.backgroundUpdateTask = UIApplication.shared.beginBackgroundTask(expirationHandler: {
            Alamofire.request("https://testomkar.herokuapp.com/log", method: .post, parameters: ["log":locations.last?.description ?? "no location"]).validate().responseJSON(completionHandler: { (responce) in
                self.endBackgroundUpdateTask()
            })
        })


    }

最佳答案

如果应用程序处于后台状态,则获取 UIBackgroundTaskIdentifier

 func scheduledLocationManager(_ manager: APScheduledLocationManager, didUpdateLocations locations: [CLLocation]) {

    print(locations.last?.description ?? "no location")

    // Get the background identifier if the app is in background mode
    if UIApplication.shared.applicationState == .background {
       backgroundUpdateTask = UIApplication.shared.beginBackgroundTask { [weak self] in
            if let strongSelf = self {
                UIApplication.shared.endBackgroundTask(strongSelf.backgroundUpdateTask)
                self.backgroundUpdateTask = UIBackgroundTaskInvalid
            }
        }
    }

    // Call the api to update the location to your server
    Alamofire.request("https://testomkar.herokuapp.com/log", method: .post, parameters: ["log":locations.last?.description ?? "no location"]).validate().responseJSON(completionHandler: { (responce) in

           //API completion block invalidate the identifier if it is not invalid already.
           if self.backgroundUpdateTask != nil && self.backgroundUpdateTask != UIBackgroundTaskInvalid {
                 UIApplication.shared.endBackgroundTask(backgroundUpdateTask)
                 self.backgroundUpdateTask = UIBackgroundTaskInvalid
           }
     })
}

关于ios - 获取位置后如何进行后台网络调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44844194/

相关文章:

ios - 如果用户在 iOS Swift 中登录,则从某个 View 开始

ios - Apple 拒绝了在没有任何非公共(public) API 的非公共(public) API 上使用的应用程序

ios - 后台获取和核心位置与时间表

ios - 隐藏 View 并应用隐藏效果 - Swift

ios - 使用 WebKit View 显示 URL - 当我点击新标签并再次返回时,我需要它恢复\刷新

ios - 按下按钮时无法使用 Swift 3 更新 SKLabel 节点

ios - 如何在 App Store 上发布 iOS 应用程序,但不允许 iPad 兼容?

iphone - iOS 键盘记录器实现

json - 在Mac Catalyst中运行的iOS应用程序中的DropInteraction中接收JSON文件

ios - UILabel 文本即使具有新值也不会更新,已尝试一切