【发布时间】:2018-11-01 20:44:13
【问题描述】:
我有一个应用程序可以查找用户位置附近的地方,但是,该应用程序在第二次运行时崩溃,但出现以下异常: 致命错误:在展开可选值时意外发现 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.
}
}
【问题讨论】:
-
第一次工作后,你杀了它然后重新启动它仍然崩溃???
-
是的。只有在我重新安装它之后它才开始工作
-
@KarthickRamesh 我通过将 viewDidAppear 代码移动到 viewDidLoad 来修复崩溃,一切似乎都正常,但我不明白问题出在哪里。我正在关注的教程使用 viewDidAppear 而不是 viewDidLoad 来解释 viewDidLoad 调用得太快了。这个link是教程
-
我认为您必须添加逻辑以在主线程中进行动画处理。在这种情况下,它甚至可以在 viewWillAppear 中工作。
-
我提到的前一点有效吗?第二点,可以修改问题吗?解决方案很简单。您需要删除旧标记并添加新标记。
标签: ios xcode google-maps swift4 gmsmapview