Mahesh NFC
Mahesh NFC

Reputation: 99

iOS 13 track user location when app is killed

I want to track user location even when app is killed by the user. I have tried below code but not working when an app is closed.

override func viewDidLoad() {
        super.viewDidLoad()
        locationManager.delegate = self
         self.checkUsersLocationServicesAuthorization()
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.allowsBackgroundLocationUpdates = true
        locationManager.requestAlwaysAuthorization()
        locationManager.requestWhenInUseAuthorization()
        locationManager.startUpdatingLocation()

    }


extension ViewController: CLLocationManagerDelegate {

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

        for location in locations {

            let objr = ["lat": "\(location.coordinate.latitude)",
                "logn": "\(location.coordinate.longitude)",
                "date": self.getCurrentDateAndTime()]
            self.saveToCoreDataAndFetchBack(objr as NSDictionary)
            //self.TriggerNotification()
        }
    }



}

Upvotes: 2

Views: 4584

Answers (1)

Fahad Masood
Fahad Masood

Reputation: 131

You have 2 options to track user location when app is killed:

1 -> Region Monitoring aka geofencing: You will setup a region to be monitored & when user enter or leave that region, the iOS system will wake up your app & notify you in application delegate about location update. https://developer.apple.com/documentation/corelocation/monitoring_the_user_s_proximity_to_geographic_regions

2-> Significant-Change location service: In this case, iOS system will wake up your app only when user's location is significantly changed. The value is around 500 meters. https://developer.apple.com/documentation/corelocation/getting_the_user_s_location/using_the_significant-change_location_service

Note: For both of these features to work, you will need 'Always' location permission from user.

Decided which method is suitable for you & then dive into the its documentation.

Upvotes: 5

Related Questions