且构网

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

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

更新时间:2023-01-25 08:51: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类,用于管理iOs中的定期位置更新。

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.

为了在后台定期获取位置,而不是耗尽设备的电池,你需要发挥位置记录的准确性,降低准确性位置管理器将其所需的准确度设置为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.

还有一种方法可以在应用程序被用户杀死之后在后台唤醒应用程序,使用app delegate让应用程序监听位置的重大变化它被杀了。当用户的位置发生大跳跃时(这可能是大约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