2016-01-24 54 views
0

我使用谷歌地圖API放置和使用座標放在蘋果地圖上的註釋。得到「意外發現無零,同時解開一個可選值」錯誤

我現在想要做的是將座標轉換爲名稱和地址,並將其用於Ekreminder。這是到目前爲止我的代碼,但我得到的錯誤「致命錯誤:意外發現零而展開的可選值」當我嘗試運行它:

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 
         // 
        }) 
+0

你真的認爲'Dictionary!'? – GoZoner

回答

0

您正在用「as!」將「City」,「State」和「Country」的字典參考依據鑄造成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 
} 
+0

已更新...感謝您的回覆 – Tim

相關問題