'MKMapView'/'showsUserLocation = true'导致模态segue出错

时间:2016-03-09 15:36:04

标签: ios swift mkmapview viewdidload

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

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

然而,当我从“关于”页面启动一个模态segue时,从一个popover(如下图所示),应用程序崩溃了:

enter image description here

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

  

致命错误:在解包可选值时意外发现nil

Xcode在我的viewDidLoad函数中指向了这一特定行:

    self.placesMap.showsUserLocation = true

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

我真的不知道如何避免这个错误,或者确定是什么导致它,所以任何帮助都表示赞赏。

1 个答案:

答案 0 :(得分:1)

基本上,有些事情正在使placesMap解除分配,然后调用viewDidLoad。您可以尝试将placesMap设置为可选而不是强制展开它,因此将!更改为属性上的?,然后将可选项链接到placesMap的调用网站中,因此{{ 1}}变为self.placesMap.showsUserLocationself.placesMap?.showsUserLocation变为self.placesMap.setRegion(region, animated: true)