我有一个应用程序,它可以在用户位置附近找到位置,但是,该应用程序在第二次运行时崩溃,出现异常:致命错误:在展开可选值时意外发现nil。在线:self.googleMapView.animate(到位置:坐标(
我检查了一下,谷歌地图视图为零,但我不明白它是如何为零的,也不明白它第一次是如何运行的。如果我删除并重新安装应用程序,它只会在随后的尝试中开始崩溃,第一次尝试时效果良好,但之后即使我重新启动应用程序,也会不断崩溃。以下的完整代码
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?
,也可以等待地图被定义以创建位置管理器。