Search code examples
swiftswiftuimapkitmkmapviewcore-location

Why my didUpdate userLocation method doesn't get called?


I have a MapKit in my view, and I want to access the userLocation data. However, the actual function

func firstMapView(_ firstMapView: MKMapView, didUpdateUserLocation userLocation: MKUserLocation){
    print("it never gets called")
}

never ends up being called.

The whole code looks like this:

import UIKit
import MapKit
import CoreLocation

class ViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate{

    @IBOutlet weak var firstMapView: MKMapView!
    let locationManager = CLLocationManager()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.requestWhenInUseAuthorization()
        
        firstMapView.delegate = self
    }
    
    
    func firstMapView(_ firstMapView: MKMapView, didUpdateUserLocation userLocation: MKUserLocation){
        print("it never gets called")
    }
    
    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
        if status == .authorizedWhenInUse {
            print("Authorized when in use detected")
            locationManager.startUpdatingLocation()
            firstMapView.showsUserLocation = true
        }
    }
}

When I run the code I get the debug message: print("Authorized when in use detected")

I saw this question, and tried to copy the things, but it didn't help.


Solution

  • Use this delegate function

    func mapView(mapView: MKMapView!, didUpdateUserLocation userLocation: MKUserLocation!) {
            print(userLocation)
    
        }
    

    delete this one

    func firstMapView(_ firstMapView: MKMapView, didUpdateUserLocation userLocation: MKUserLocation){
            print("it never gets called")
        }