我正在开发一个小型地图应用程序,该应用程序允许用户查看其当前位置。我有执行此操作的相关代码,它似乎按预期工作:

import UIKit
import MapKit
import CoreLocation

class ViewController: UIViewController, MKMapViewDelegate, CLLocationManagerDelegate, UISearchBarDelegate, UIPopoverPresentationControllerDelegate {

    // CLlocation
    var location: CLLocation!
    let locationManager = CLLocationManager()

    // Map variables
    var searchController:UISearchController!
    var annotation:MKAnnotation!
    var localSearchRequest:MKLocalSearchRequest!
    var localSearch:MKLocalSearch!
    var localSearchResponse:MKLocalSearchResponse!
    var error:NSError!
    var pointAnnotation:MKPointAnnotation!
    var pinAnnotationView:MKPinAnnotationView!

    // IBOutlets
    @IBOutlet weak var placesMap: MKMapView!

    // Location function
    func locationManager(manager: CLLocationManager, didUpdateqLocations locations: [CLLocation]) {
        let location = locations.last
        let center = CLLocationCoordinate2D(latitude: location!.coordinate.latitude, longitude: location!.coordinate.longitude)
        let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))
        self.placesMap.setRegion(region, animated: true)
        self.locationManager.stopUpdatingLocation()
    }

    func locationManager(manager: CLLocationManager, didFailWithError error: NSError)
    {
        print("Error code: " + error.localizedDescription)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        self.locationManager.delegate = self
        self.locationManager.desiredAccuracy = kCLLocationAccuracyBest
        self.locationManager.requestWhenInUseAuthorization()
        self.locationManager.startUpdatingLocation()
        self.placesMap.showsUserLocation = true
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}


但是,当我从弹出窗口(如下图所示)向“关于”页面启动模式搜索时,应用程序崩溃:

ios - 'MKMapView'/'showsUserLocation = true'导致模态segue错误-LMLPHP

我查看了终端机给我的错误,这是


  致命错误:解开Optional值时意外发现nil


Xcode将我指向viewDidLoad函数中的这一行:

    self.placesMap.showsUserLocation = true


当我从代码中删除该特定行时,位置功能不再起作用,这是显而易见的。我已经检查了MKMapView的出口,这似乎是正确的。

我真的不知道如何避免此错误,或者确定是什么原因导致的,因此不胜感激。

最佳答案

基本上,是使placesMap解除分配,然后调用viewDidLoad的原因。您可以尝试将placesMap设置为可选,而不是强行解包,因此将!更改为属性上的?,然后将可选链接链接到placesMap的调用位置,使self.placesMap.showsUserLocation变为self.placesMap?.showsUserLocationself.placesMap.setRegion(region, animated: true)变为self.placesMap?.setRegion(region, animated: true)

10-08 15:44