如何在地图上显示当前位置?

How do i show current location on map?

在我的代码中,我试图访问用户的当前位置并将其显示在地图上。我目前遇到致命错误 Thread 1: Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value 错误在 ViewDidLoad 内。这样做的正确方法是什么?我拥有所有 3 个正确的隐私位置 *始终和使用时,使用时使用说明,始终使用说明 *

    import UIKit
    import MapKit
    import CoreLocation

    class MapViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate {

        private var locationManager: CLLocationManager!
        private var currentLocation: CLLocation?

        //let locationManager = CLLocationManager()
        let mapView = MKMapView()
        //var currentLocation: CLLocation!

        override func viewDidLoad() {
            super.viewDidLoad()



            if CLLocationManager.locationServicesEnabled(){
                locationManager.requestAlwaysAuthorization()//This where the fatal error appears

                locationManager.requestWhenInUseAuthorization()////This where the fatal error appears

                locationManager = CLLocationManager()
                locationManager.delegate = self
                locationManager.desiredAccuracy = kCLLocationAccuracyBest
                locationManager.startUpdatingLocation()
            }
            mapView.delegate = self
            mapView.mapType = .standard
            mapView.isZoomEnabled = true
            mapView.isScrollEnabled = true

            let leftMargin:CGFloat = 10
            let topMargin:CGFloat = 60
            let mapWidth:CGFloat = view.frame.size.width
            let mapHeight:CGFloat = view.frame.size.width

            mapView.frame = CGRect(x: leftMargin, y: topMargin, width: mapWidth, height: mapHeight)

            view.addSubview(mapView)


            if let coor = mapView.userLocation.location?.coordinate{
                mapView.setCenter(coor, animated: true)
            }


        }

        func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
            defer { currentLocation = locations.last }

            if currentLocation == nil {
                // Zoom to user location
                if let userLocation = locations.last {
                    let viewRegion = MKCoordinateRegion(center: userLocation.coordinate, latitudinalMeters: 2000, longitudinalMeters: 2000)
                    mapView.setRegion(viewRegion, animated: false)
                }
            }

        }
        func checkLocationAuthorization(authorizationStatus: CLAuthorizationStatus? = nil) {
            switch (authorizationStatus ?? CLLocationManager.authorizationStatus()) {
            case .authorizedAlways, .authorizedWhenInUse:
                locationManager.startUpdatingLocation()
                mapView.showsUserLocation = true
            case .restricted, .denied:
                // show alert instructing how to turn on permissions
                print("Location Servies: Denied / Restricted")
            case .notDetermined:
                locationManager.requestWhenInUseAuthorization()
            }
        }




    }

在创建实例之前将 requestAlwaysAuthorizationrequestWhenInUseAuthorization 分配给 locationManager 会使应用程序崩溃。

更新如下代码,

if CLLocationManager.locationServicesEnabled(){

            locationManager = CLLocationManager()
            locationManager.requestAlwaysAuthorization()
            locationManager.requestWhenInUseAuthorization()
            locationManager.delegate = self
            locationManager.desiredAccuracy = kCLLocationAccuracyBest
            locationManager.startUpdatingLocation()
        }