i can find a current location of user when app is running . But i can't find location when app is killed. How can i find location ?
This code give me a current location ;
func determineMyCurrentLocation() {
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
if CLLocationManager.locationServicesEnabled() {
locationManager.startUpdatingLocation()
locationManager.startUpdatingHeading()
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let userLocation:CLLocation = locations[0] as CLLocation
print("user latitude = \(userLocation.coordinate.latitude)")
print("user longitude = \(userLocation.coordinate.longitude)")
latitude = userLocation.coordinate.latitude
longitude = userLocation.coordinate.longitude
UserDefaults(suiteName: "group.com.ReelKapi")!.set(latitude, forKey:"latitude")
UserDefaults(suiteName: "group.com.ReelKapi")!.set(longitude, forKey:"longitude")
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error)
{
print("Error \(error)")
}
A highly recommended reading .
First, a user of the app must allow your app to monitor location in the background. I see that you are requesting that permission with requestAlwaysAuthorization()
, so that part is covered.
Also, you have to set allowsBackgroundLocationUpdates to YES.
Next, you should add a specific Background Mode location
key to your app bundle's plist.
With all of that set up, in the BG mode your app will be able to get events from a standard location service your code is using now ( startUpdatingLocation()
).
If your app is killed by a user or by the iOS, it would be loaded up again to the background to receive region entry/exit events, visits events or significant location updates. So, if your want your app to be relaunched your have to use one of those.
When app is getting killed OS don't allow to run any code so you don't get any update although you can use previously saved location in nsuserDefaults. Only When user relaunch your application it comes in foreground state you can get a update location from location Manager.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.