Pelin
Pelin

Reputation: 43

How to call "didUpdateLocation" method from viewDidLoad?

I am making a weather app which gets temperature info by sending current coordinates. So I am using CLLocationManager. I haven't make any HTTP request yet. I would like to see "Location Unavailable" on my screen but it is not working.

I am following a tutorial and wrote exactly same code but in tutorial it is working. In debug session, it doesn't jump to didFailwithError or didUpdateLocations methods.I added all necessary things in my info.plist and my phone's location services are open. According to my research locationManager.startUpdatingLocation() should call automatically these methods but when I run my app nothing appears on UI.

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
   print("you got the location")

}

//Write the didFailWithError method here:
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
    print(error)
    cityLabel.text = "Location Unavaiable"
}

And

let locationManager = CLLocationManager ()
override func viewDidLoad() {
    super.viewDidLoad()

    //TODO:Set up the location manager here.
    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters
    locationManager.requestWhenInUseAuthorization()
    locationManager.startUpdatingLocation()

}

Upvotes: 0

Views: 515

Answers (1)

Desdenova
Desdenova

Reputation: 5378

You are updating location too soon, in fact before you get the permission from user.

After you ask for permission

locationManager.requestWhenInUseAuthorization()

Delegate method will call

func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {

}

Now its time to start updates. Guarding the status is a good idea since you don't want to start updating unless user permits it.

func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {

        guard status == .authorizedWhenInUse else { return }
        manager.startUpdatingLocation()

}

Now you'll get location updates

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

        print(locations)

}

Upvotes: 2

Related Questions