Reputation: 3759
I have written this program, it is work when the app is displaying on screen
If the app in background, it stop to print the latitude, when I resume the app, it will start to print again.
I have enabled background modes in xcode, and also checked Location updates
, why my app still not running in background?
If the app is running, just the print
function does not work in background, how can I know the app is running?
class ViewController: UIViewController,
CLLocationManagerDelegate {
var locationManager: CLLocationManager = CLLocationManager()
var startLocation: CLLocation!
func locationManager(_ manager: CLLocationManager,
didUpdateLocations locations: [CLLocation])
{
let latestLocation: CLLocation = locations[locations.count - 1]
print(latestLocation.coordinate.latitude)
}
override func viewDidLoad() {
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.delegate = self
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
startLocation = nil
}
}
Upvotes: 1
Views: 561
Reputation: 8322
If your app uses location in the background ).you have to set allowsBackgroundLocationUpdates
to YES in addition to setting the background mode capability in Info.plist
. Otherwise location updates are only delivered in foreground.
if CLLocationManager is first called startUpdatingLocation
method, and in the projectname-Info.plist file is added Required Background Modes
-> App registers for location updates.
Upvotes: 1
Reputation: 1803
First, your problem:
locationManager.requestWhenInUseAuthorization()
This requests your location manager to update its location only when your app is in the foreground. You have to change this to:
locationManager.requestAlwaysAuthorization()
If it still doesn't work, make sure your location manager is firing updates at all by adding a print statement in the delegate functions.
Second, how to print stuff in the background:
My favorite way is to log things in UserDefaults, because those persist across app restarts. I will set my print statements as the value to a log
key for example. Upon restart I will read the contents of UserDefaults from the log
key.
Upvotes: 2