在 GMSMAPVIEW 上 运行 多次时应用程序崩溃

App crashes when run more than once on GMSMAPVIEW

我有一个应用程序可以找到用户位置附近的地方,但是,该应用程序在第二次运行时崩溃了,但出现以下异常: 致命错误:在展开 Optional 值时意外发现 nil。 在线的: self.googleMapView.animate(toLocation: 坐标)

我检查了一下,googleMapView 是 nil,但我不明白它是怎么变成 nil 的,也不明白它是如何 运行 第一次的。如果我删除并重新安装应用程序,它只会在后续尝试时开始崩溃,它在第一次尝试时运行良好,但之后即使我重新启动应用程序,它也会继续崩溃。完整代码如下

import UIKit
import GoogleMaps
import GooglePlacePicker
import MapKit

 class MapViewController: UIViewController, CLLocationManagerDelegate {
var currentLongitude: CLLocationDegrees = 0
var currentLatitude: CLLocationDegrees = 0
var locationManager: CLLocationManager!
var placePicker: GMSPlacePickerViewController!
var googleMapView: GMSMapView!

@IBOutlet weak var mapViewContainer: MKMapView!

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    self.googleMapView = GMSMapView(frame: self.mapViewContainer.frame)
    self.googleMapView.animate(toZoom: 18.0)
    self.view.addSubview(googleMapView)
}

override func viewDidLoad() {
    super.viewDidLoad()
    self.locationManager = CLLocationManager()
    self.locationManager.delegate = self
    self.locationManager.requestAlwaysAuthorization()
    self.locationManager.requestWhenInUseAuthorization()
    self.locationManager.startUpdatingLocation()
}

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    if let location:CLLocation = locations.last {
        self.currentLatitude = location.coordinate.latitude
        self.currentLongitude = location.coordinate.longitude
    }
    else {
        print("Location Error")
    }

    let coordinates = CLLocationCoordinate2DMake(self.currentLatitude, self.currentLongitude)
    let marker = GMSMarker(position: coordinates)
    marker.title = "I am here"
    marker.map = self.googleMapView
    self.googleMapView.animate(toLocation: coordinates)
}



private func locationManager(manager: CLLocationManager,
                     didFailWithError error: Error){
    print("An error occurred while tracking location changes : \(error.localizedDescription)")
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

}

崩溃是不言自明的:

您正在 viewDidLoad 中设置您的位置代理,但在 viewDidAppear 中创建地图。

如果 iOS 知道该位置,您将在 viewDidAppear 调用之前收到消息:self.googleMapView.animate(toLocation: coordinates),您的地图仍然是 nil

您可以将您的地图定义为可选:var googleMapView: GMSMapView?,或者您可以等待您的地图被定义以创建您的位置管理器。