【问题标题】:Swift - Google Map crashes with 'unexpectedly found nil' errorSwift - Google Map 因“意外发现 nil”错误而崩溃
【发布时间】:2016-12-27 13:25:52
【问题描述】:

我正在尝试将 GoogleMap 设置为 UIView 并将其添加为子视图。但是,在运行应用程序时出现此错误:

致命错误:在展开可选值时意外发现 nil

它在代码行崩溃:

mapView.camera = camera

这是我的完整 ViewController 代码:

class LocationViewController: UIViewController {
    @IBOutlet weak var mapView: GMSMapView!

    override func viewDidLoad() {
        super.viewDidLoad()

        let camera = GMSCameraPosition.camera(withLatitude: 15.4989, longitude: 73.8278, zoom: 6)
        mapView.camera = camera
        mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera)
        mapView.isMyLocationEnabled = true
        mapView.settings.myLocationButton = true
        self.view.addSubview(self.mapView)
    }
}

我浏览了其他一些类似的 SO 线程,它们都有相同的代码。在我的情况下,用户界面因此错误而冻结并崩溃。我做错了什么?

编辑

是的,我已将 UIView 的自定义类设置为 GMSMapView

【问题讨论】:

  • 你在哪一行出错了?
  • @Jecky 在mapView.camera = camera
  • 检查我的答案
  • 在 Storyboard 中检查您的 IBOutlet 连接
  • 您是否将 GMSMapView 类赋予 Storyboard 中的视图

标签: ios swift google-maps swift3 xcode8


【解决方案1】:

你能用下面的代码试试吗:

override func viewDidLoad() {
        super.viewDidLoad()

        let camera = GMSCameraPosition.camera(withLatitude: 15.4989, longitude: 73.8278, zoom: 6)
        mapView.camera = camera
        mapView.isMyLocationEnabled = true
        mapView.settings.myLocationButton = true
        self.view.addSubview(self.mapView)
    }

【讨论】:

  • 你做了什么改变?
  • 您的地图视图框架
  • 代码在swift-3 bro中有点不同:/
  • 仍然崩溃,应该是弱引用还是强引用?
  • 它一定很弱,如果您使用故事板连接它,请参考我更新的答案
【解决方案2】:

你必须这样做

你必须把框架给GMSMapview
在这一行self.view.bounds,你必须设置你的自定义view

let camera = GMSCameraPosition.camera(withLatitude: 15.4989,
                                      longitude:  73.8278,
                                      zoom: 6)
let mapView = GMSMapView.map(withFrame: self.view.bounds, camera: camera)

【讨论】:

    【解决方案3】:

    这是 swift 3.0 中的语法

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) 
    {
        print(locations)
        mapview.delegate = self
     currentLocation =     CLLocationCoordinate2D(latitude:CLLocationDegrees(locations[0].coordinate.latitude), longitude:CLLocationDegrees(locations[0].coordinate.longitude))
        mapview.camera = GMSCameraPosition.camera(withTarget:locations[0].coordinate, zoom: 10.0)
    mapview.isMyLocationEnabled = true
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-18
      • 2020-11-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多