Reputation: 33
I have created a singleton LocationManager class to handle location updates in my application. In the first view controller the shared instance is accessed in viewDidLoad
and a call to getCurrentLocation
is made. "Getting users location..." prints to the console however the delegate method didUpdateLocations
on the location manager is never called and the location is not updated. I have the required keys in the info.plist and the expected permissions prompts show.
I have a feeling this is a threading issue with the LocationManager
falling out of scope but I'm not sure, would be great if someone could point me in the right direction !
Location Manager:
import Foundation
import CoreLocation
class LocationManager: NSObject, CLLocationManagerDelegate {
static let shared = LocationManager()
var manager: CLLocationManager!
override init() {
super.init()
self.manager = CLLocationManager()
self.manager.delegate = self
if CLLocationManager.authorizationStatus() == .notDetermined {
self.manager.requestWhenInUseAuthorization()
}
self.manager.desiredAccuracy = kCLLocationAccuracyBest
}
public func getCurrentLocation(){
print("Getting users location...")
self.manager.startUpdatingLocation()
}
func locationManager(manager:CLLocationManager, didUpdateLocations locations:[AnyObject]) {
self.manager.stopUpdatingLocation()
print("locations = \(locations)")
}
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
print(error.localizedDescription)
}}
ViewController:
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var savedAreasTableView: UITableView!
@IBOutlet weak var noSavedAreasLabel: UILabel!
var manager: LocationManager! = LocationManager.shared
override func viewDidLoad() {
super.viewDidLoad()
self.noSavedAreasLabel.text = "You have no saved areas available !\nTo add some, search for a location and then favourite it."
//Check here to see if user has any favourited areas
self.savedAreasTableView.isHidden = true
self.noSavedAreasLabel.isHidden = false
self.manager.getCurrentLocation()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Upvotes: 1
Views: 451
Reputation: 3939
The correct delegate function is this:
func locationManager(_ manager: CLLocationManager,
didUpdateLocations locations: [CLLocation])
Upvotes: 1