I have a Swift app that I am trying to update the location when the app is returned from the background, but it doesn't seem to work when returned from the background.
On launch of the app, I'll get the location just fine. After getting the location I call stopUpdatingLocation() so I don't continue to get the location: locationManager.stopUpdatingLocation()
Then, in my AppDelegate.swift I startUpdatingLocation again:
func applicationWillEnterForeground(application: UIApplication) {
ViewController().locationManager.startUpdatingLocation()
}
This is my code so far:
import UIKit
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate {
var locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
println("Error while updating location " + error.localizedDescription)
}
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
var userLocation:CLLocation = locations[0] as CLLocation
println("\(userLocation.coordinate.latitude),\(userLocation.coordinate.longitude)")
locationManager.stopUpdatingLocation()
}
}
However, whenever I background the app (click home), and then return to the app the location isn't updated. Any idea what I might be doing wrong here?