我有一个应用程序可以找到用户所在位置附近的地方,但是,该应用程序第二次运行时发生崩溃,但有一个例外: 致命错误:解开Optional值时意外发现nil。 在线: self.googleMapView.animate(toLocation:坐标)
我检查了一下,而googleMapView为零,但我不知道它如何为零或如何第一次运行。如果我删除并重新安装该应用程序,它只会在以后的尝试中崩溃,但在第一次尝试时它仍能正常工作,但是即使我重新启动该应用程序,它也仍然崩溃。完整代码如下
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.
}
}
答案 0 :(得分:0)
崩溃是不言而喻的:
您正在viewDidLoad
中设置位置的委托,但在viewDidAppear
中创建地图。
如果iOS知道该位置,您将在viewDidAppear
呼叫之前收到消息,因此在行self.googleMapView.animate(toLocation: coordinates)
中,您的地图仍为nil
您可以将地图定义为可选的var googleMapView: GMSMapView?
,也可以等待定义地图来创建位置管理器。