【问题标题】:get the "unexpectedly found nil while unwrapping an Optional value" error得到“在展开可选值时意外发现 nil”错误
【发布时间】:2016-01-24 14:28:58
【问题描述】:

我正在使用 google Places api 并使用坐标在苹果地图上添加注释。

我现在要做的是将坐标转换为名称和地址,并将其用于 Ekreminder。到目前为止,这是我的代码,但是当我尝试运行它时出现错误“致命错误:在展开可选值时意外发现 nil”:

    addLocationReminderViewController.name = self.mapItemData.placemark.name

    // Construct the address
    let dic = self.mapItemData.placemark.addressDictionary as Dictionary!
    let city = dic["City"] as! String
    let state = dic["State"] as! String
    let country = dic["Country"] as! String
    addLocationReminderViewController.address = "\(city), \(state), \(country)"
}

编辑这是我获取信息的方式:

                    if data != nil{
                    let dic = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableLeaves) as!  NSDictionary

                    let lat = dic["results"]?.valueForKey("geometry")?.valueForKey("location")?.valueForKey("lat")?.objectAtIndex(0) as! Double
                    let lon = dic["results"]?.valueForKey("geometry")?.valueForKey("location")?.valueForKey("lng")?.objectAtIndex(0) as! Double
                    let point = MKPointAnnotation()
                    point.coordinate = CLLocationCoordinate2D(latitude: lat, longitude: lon)
                    point.title = self.resultsArray[indexPath.row]
                    let region = MKCoordinateRegion(center: point.coordinate, span: MKCoordinateSpan(latitudeDelta: 0.1, longitudeDelta: 0.1))
                    dispatch_async(dispatch_get_main_queue(), { () -> Void in
                        self.mapView.setRegion(region, animated: true)
                        self.mapView.addAnnotation(point)
                        self.mapView.selectAnnotation(point, animated: true)
                        //
                        let placemark = MKPlacemark(coordinate: point.coordinate, addressDictionary: nil)
                        let mapItem = MKMapItem(placemark: placemark)
                        self.mapItemData = mapItem
                        //
                    })

【问题讨论】:

  • 你的意思是Dictionary!吗?

标签: swift mapkit coordinates eventkit


【解决方案1】:

您正在使用as! 将“城市”、“州”和“国家”的字典引用“盲目”转换为String。如果其中任何一个在字典中不存在或不是字符串,那么您将收到致命错误。

您打算如何处理格式错误的字典?你可以使用

if let city    = dic["City"]    as? String,
   let state   = dic["State"]   as? String,
   let country = dic["Country"] as? String {
  // you now have your values
  addLocationReminderViewController.address = "\(city), \(state), \(country)"
}
else {
 // something is wrong
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-07
    • 2016-01-26
    • 1970-01-01
    相关资源
    最近更新 更多