【问题标题】:myLocationEnabled - Unexpectedly found nil while unwrappingmyLocationEnabled - 展开时意外发现 nil
【发布时间】:2016-02-06 12:23:43
【问题描述】:

我只是想使用 GoogleMaps API 在我的 MapViewController 中获取用户位置。 我环顾四周,无法弄清楚为什么我不断出现致命错误:在这个特定位置展开时意外发现 nil 和 Optional 值。

这是我的代码:

class MapViewController: UIViewController {

    let locationManager = CLLocationManager()
    @IBOutlet weak var mapView: GMSMapView!

    override func viewDidLoad() {
        super.viewDidLoad()

        locationManager.delegate = self
        locationManager.requestWhenInUseAuthorization()

        let camera = GMSCameraPosition.cameraWithLatitude(-34.9290, longitude:138.6010, zoom:10)
        let mapView = GMSMapView.mapWithFrame(CGRectZero, camera:camera)
        mapView.mapType = kGMSTypeNormal
        print("Calling addMarker")
        // addMarker()
        self.view = mapView
        }

extension MapViewController: CLLocationManagerDelegate {
    func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
        if status == .AuthorizedWhenInUse {
            locationManager.startUpdatingLocation()
            mapView.myLocationEnabled = true
            mapView.settings.myLocationButton = true
        }
    }

    func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        if let location = locations.first {
            mapView.camera = GMSCameraPosition(target: location.coordinate, zoom: 15, bearing: 0, viewingAngle: 0)
            locationManager.stopUpdatingLocation()
        }
    }
}

这是我得到错误的地方:

!(http://imgur.com/qxxf0SV)

我知道mapView.myLocationEnabled 返回 nil 但不明白为什么/如何。

【问题讨论】:

    标签: ios swift mkmapview cllocationmanager


    【解决方案1】:

    很可能是 mapView 为 nil,而不是 mapView.myLocationEnabled。当您遇到崩溃时,请尝试以下 lldb 命令:

    po mapView
    

    这会告诉你确切的。

    didChangeAuthorizationStatus 委托可能是从后台调用或在视图完成之前调用的。您应该将这些扩展移动到您的 AppDelegate 中。

    【讨论】:

    • 感谢您的回复。确实你是对的,po mapView 显示 mapView 是一个未解析的标识符。然而,将扩展移动到 AppDelegate 并没有修复错误:(
    • IBOutlet 是否连接到 Interface Builder 中的相应视图?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-06
    • 1970-01-01
    • 1970-01-01
    • 2017-01-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多