Run a Swift 2.0 app forever in background to update location to server

爷,独闯天下 提交于 2019-11-27 19:11:29
Daniel Ormeño

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

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.

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.

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.

Hope this helps.

Update

In Swift 2 you'll also need:

self.locationManager.allowsBackgroundLocationUpdates = true

You can use library for background location tracking, example of use:

    var backgroundLocationManager = BackgroundLocationManager()

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool {

     backgroundLocationManager.startBackground() { result in
            if case let .Success(location) = result {
                LocationLogger().writeLocationToFile(location: location)
            }
    }

    return true
}

It's working when application is killed or suspended.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!