Reputation: 1240
I'm having some trouble getting the user's current location. I realize there are many questions on this topic, but I have read them and done exactly what the Apple documentation tells me to do and still it doesn't work.
I have the following code in my MasterViewController:
class MasterViewController: UITableViewController, CLLocationManagerDelegate {
var detailViewController: DetailViewController? = nil
var locationManager:CLLocationManager!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.navigationItem.leftBarButtonItem = self.editButtonItem()
let addButton = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "printPlace:")
self.navigationItem.rightBarButtonItem = addButton
if let split = self.splitViewController {
let controllers = split.viewControllers
self.detailViewController = controllers[controllers.count-1].topViewController as? DetailViewController
}
if !CLLocationManager.locationServicesEnabled() {
println("location services disabled")
}
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.distanceFilter = kCLDistanceFilterNone
locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()
}
func locationManager(manager:CLLocationManager, didUpdateLocations locations:[AnyObject]) {
println("found location")
}
@IBAction func printPlace(sender: AnyObject) {
let currentLocation: CLLocationCoordinate2D = locationManager.location.coordinate
println("\(currentLocation.latitude) , \(currentLocation.longitude)")
}
I also added the NSLocationWhenInUseUsageDescription key to my info.plist. However, when I run this code, didUpdateLocations is never called, and printPlace gives a fatal error because locationManager.location is nil. Can anyone see what I'm doing wrong here?
Upvotes: 0
Views: 303
Reputation: 5248
Ah, the issue might be that you said you updated your .plist for NSLocationWhenInUseUsageDescription but in your code you call locationManager.requestAlwaysAuthorization()
which is something different. You either need to add the proper one to the .plist (NSLocationAlwaysUsageDescription), or request only for when in use like this: locationManager.requestWhenInUseAuthorization()
.
Also, as the comment on your original post points out, it should be NSLocationWhenInUseUsageDescription, not NSLocationWhenInUsageDescription
Upvotes: 3