I have the following code to get location updates (iOS 7):
import UIKit
import CoreLocation
class FirstViewController: UIViewController, CLLocationManagerDelegate {
var locationManager: CLLocationManager!
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@IBAction func startTracking(sender : AnyObject) {
NSLog("Start tracking")
if (locationManager == nil) {
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation
locationManager.distanceFilter = kCLDistanceFilterNone
locationManager.pausesLocationUpdatesAutomatically = false
}
locationManager.startUpdatingLocation()
}
@IBAction func stopTracking(sender : AnyObject) {
NSLog("Stop tracking")
stopUpdatingLocation()
}
func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
NSLog("Error" + error.description)
}
func locationManager(manager:CLLocationManager, didUpdateLocations locations:AnyObject[]) {
println("locations = \(locations)")
}
func locationManager(manager: CLLocationManager!,
didChangeAuthorizationStatus status: CLAuthorizationStatus) {
switch status {
case CLAuthorizationStatus.Restricted:
locationStatus = "Access: Restricted"
break
case CLAuthorizationStatus.Denied:
locationStatus = "Access: Denied"
break
case CLAuthorizationStatus.NotDetermined:
locationStatus = "Access: NotDetermined"
shouldIAllow = true
break
default:
locationStatus = "Access: Allowed"
shouldIAllow = true
}
NSLog(locationStatus)
}
}
I get only one update in the didUpdateLocations
: after calling startTracking
the didUpdateLocations
will be called only once and in 5 seconds GPS indicator disappears.
Some details:
- application is authorized to use location services
- application is in foreground
- interestingly enough: if I put breakpoint in the
didUpdateLocations
it will be hit 4 - 5 time.
I have seen answers to the similar questions here (like Implement CLLocationManagerDelegate methods in Swift), but it still doesn't work for me.
What am I doing wrong?
Thanks!
In
Swift 4
you can use this,Try implementing this method to see if your location manager is being paused:
If you're getting paused, try changing the accuracy to
kCLLocationAccuracyBest
.Xcode 6 made lots of additions to Location Services.
1) You need to change your info.plist file to include the String "NSLocationWhenInUseUsageDescription" key. The value of this will be your applications reasoning for turning on location services: "Using location services to track your run".
2) use "[self.locationManager requestWhenInUseAuthorization];" in your code to cause the pop-up to appear with your above string.
More info is on the WWDC 2014 videos.
This is what resolved the issue - I've added a very short sleep to the
didUpdateLocations
:I agree with @Mike that it looks like a very weird fix, but it is a fix. If somebody will find a better explanation/answer, please, post it.