How to use Swift to run in background to provide current location?

iOSiPhone/iPadMobile DevelopmentSwift

To get background location in swift we need to go through a few steps

Get the permissions from the user, in your info.plist file add Privacy- Location always and

when in usage Description, Privacy – When in usage description and add their respective description.

After that, you need to import the CoreLocation framework which will enable you to use all the location related libraries and methods. Then you need to get permission from the user to use the location. For that, we need to create a CLLocationManager Object and get authorization.

var locationManager: CLLocationManager?
override func viewDidLoad() {
   locationManager = CLLocationManager()
   locationManager?.delegate = self

Now when you run the app and if it requires location in the specific module it will ask for user permission. After that you can add the following codes to start monitoring location changes, to update location etc.

locationManager.allowsBackgroundLocationUpdates = true

Once this is done you can use the didUpdateLocation Method of CLLocationManagerDelegate to update the location to your server in the background.

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
   // Hit api to update location

Now whenever the location is updated, this method of CLLocationManagerDelegate would be called and inside this we can write the code to update location on the server.

Published on 29-Jan-2019 12:13:05