В своем коде я пытаюсь получить доступ к текущему местоположению пользователя и показать его на карте. В настоящее время я получаю фатальную ошибку 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()
}
}
}