为什么我的didUpdate userLocation方法没有被调用?

问题描述

我的视图中有一个MapKit,我想访问userLocation数据。但是,实际功能

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

永远不会被调用

整个代码如下:

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
        }
    }
}

运行代码时,我收到调试消息:print("Authorized when in use detected")

我看到了this的问题,并试图复制内容,但没有帮助。

解决方法

使用此委托函数

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

    }

删除此

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