且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

永远在后台运行 Swift 2.0 应用程序以将位置更新到服务器

更新时间:2023-01-25 08:38:55

在 IOS 中定期位置更新有点棘手.有一个很好的线程讨论了这个问题,你可以阅读更多 这里

Periodic location updates are a bit tricky in IOS.There's a good thread that discusses this, you can read more here

无论您的计时器是否正在运行,iOS 都会在几分钟后终止您的应用.不过有一种方法可以解决这个问题,我在编写离子应用程序时必须做类似的事情,这样你就可以查看这个 这里,该链接有一个 swift 类,用于管理 iO 中的定期位置更新.

iOS will terminate your app after a few minutes, regardless if your timer is running or not. There is a way around this though, I had to do something similar when writing an ionic app so you can check out the code for this here, that link has a swift class that manages the periodic location updates in iOs.

为了在后台获取周期性位置,并且不耗尽设备的电池,您需要使用位置记录的准确性,降低位置管理器的准确性,将其 desiredAccuracy 设置为 kCLLocationAccuracyThreeKilometers,然后,每个您需要在 60 秒内将准确度更改为 kCLLocationAccuracyBest,这将使代理能够获得新的准确位置更新,然后将准确度恢复为低.每次收到更新时都需要初始化计时器.

In order to get periodic locations in the background, and not drain the battery of the device, you need to play with the accuracy of the location records, lower the accuracy of the location manager setting its desiredAccuracy to kCLLocationAccuracyThreeKilometers, then, every 60 seconds you need to change the accuracy to kCLLocationAccuracyBest, this will enable the delegate to get a new, accurate location update, then revert the accuracy back to low. The timer needs to be initialized every time an update is received.

还有一种方法可以在应用被用户杀死后在后台唤醒它,使用应用委托让应用在被杀死之前监听位置的重大变化.当用户的位置发生很大的跳跃(可能是 200 毫秒左右)时,这将在后台唤醒应用程序.当应用唤醒时,停止监控重大变化并像往常一样重新启动位置服务以继续定期更新.

There's also a way to wake up the app in the background after its been killed by the user, use the app delegate to have the app listen for significant changes in location before its killed. This will wake up the app in the background when the user's location makes a big jump (can be around 200ms). When the app wakes up, stop monitoring for significant changes and restart the location services as usual to continue the periodic updates.

希望这会有所帮助.

更新

在 Swift 2 中,您还需要:

In Swift 2 you'll also need:

self.locationManager.allowsBackgroundLocationUpdates = true