fatal error: unexpectedly found nil while unwrapping an Optional value (lldb)

fatal error: unexpectedly found nil while unwrapping an Optional value (lldb)

我正在尝试在 google 地图中添加标记,在 swift 中长按 !!!!! 当我添加下面的代码时,出现了一些错误!

class ViewController: UIViewController, CLLocationManagerDelegate, UIGestureRecognizerDelegate {

    var mapView: GMSMapView?
    var locationManager = CLLocationManager()
    var locationMarker: GMSMarker!

    override func viewDidLoad() {
        super.viewDidLoad()

        let longPressRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(ViewController.handleLongPress(_:)))
        self.mapView!.addGestureRecognizer(longPressRecognizer)

        GMSServices.provideAPIKey("AIzaSyBw95wEhcSiSBmPWuYkiK0_IBnZQK-Lm7I")


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

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

    func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        let userLocation = locations.last
        let center = CLLocationCoordinate2D(latitude: userLocation!.coordinate.latitude, longitude: userLocation!.coordinate.longitude)

        let camera = GMSCameraPosition.cameraWithLatitude(userLocation!.coordinate.latitude,
                                                          longitude: userLocation!.coordinate.longitude, zoom: 16)
        let mapView = GMSMapView.mapWithFrame(CGRectZero, camera: camera)
        mapView.myLocationEnabled = true
        mapView.settings.myLocationButton = true
        view = mapView

 // marker with optional position
       let  position = CLLocationCoordinate2DMake(10, 10)
        let marker = GMSMarker(position: position)


        marker.opacity = 0.6
        marker.position = center
        marker.title = "Current Location"
        marker.snippet = ""
        marker.map = mapView
        //mapView.clear()
        //locationManager.stopUpdatingLocation()

        }
    func handleLongPress(recognizer: UILongPressGestureRecognizer)
    {
        if (recognizer.state == UIGestureRecognizerState.Began)
        {
            let longPressPoint = recognizer.locationInView(self.mapView);
            let coordinate = mapView!.projection.coordinateForPoint(longPressPoint )
            //Now you have Coordinate of map add marker on that location

        }}


    }

You can see error page here !!!!

在 didUpdateLocations 方法中引发错误,因为它似乎有时我们没有获取位置,所以它在那里传递 nil。

因此您可以使用 try catch 块或使用 If let 语法来避免此问题。

问题是您使用地图视图时没有对其进行初始化

var mapView: GMSMapView?

在 viewDidLoad 中

    self.mapView!.addGestureRecognizer(longPressRecognizer)