我只是想使用GoogleMaps API在我的MapViewController中获取用户位置。 我到处都环顾四周,无法弄清楚为什么我会不断发生致命的错误:在这个特殊的地方,在展开和意外值时意外地发现了nil。
这是我的代码:
class MapViewController: UIViewController {
let locationManager = CLLocationManager()
@IBOutlet weak var mapView: GMSMapView!
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self
locationManager.requestWhenInUseAuthorization()
let camera = GMSCameraPosition.cameraWithLatitude(-34.9290, longitude:138.6010, zoom:10)
let mapView = GMSMapView.mapWithFrame(CGRectZero, camera:camera)
mapView.mapType = kGMSTypeNormal
print("Calling addMarker")
// addMarker()
self.view = mapView
}
extension MapViewController: CLLocationManagerDelegate {
func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
if status == .AuthorizedWhenInUse {
locationManager.startUpdatingLocation()
mapView.myLocationEnabled = true
mapView.settings.myLocationButton = true
}
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let location = locations.first {
mapView.camera = GMSCameraPosition(target: location.coordinate, zoom: 15, bearing: 0, viewingAngle: 0)
locationManager.stopUpdatingLocation()
}
}
}
这是我收到错误的地方:
我知道mapView.myLocationEnabled
正在返回,但不知道为什么/如何。
答案 0 :(得分:0)
很可能是mapView是nil,而不是mapView.myLocationEnabled。当你遇到崩溃时,请尝试以下lldb命令:
po mapView
这将完全告诉你。
didChangeAuthorizationStatus委托可能是从后台调用或在视图完成之前调用的。您应该将这些扩展移动到AppDelegate中。