我是新手。我正在尝试使用他们的sdk创建对Google API的调用,以便将任何输入的地址转换为谷歌地图上的长的纬度位置。
我认为从教程http://www.appcoda.com/google-maps-api-tutorial/开始,然后解剖它会更容易。但我似乎无法让这条特定的线路起作用。它将在dicitonary line上出现“error-exc-bad-instruction-code-exc-i386-invop-subcode-0x0”。我阅读了迄今为止反向地理编码的其他示例工作,它们看起来非常相似,但都没有工作。我做错了什么?
let dictionary: Dictionary<NSObject, AnyObject> =
NSJSONSerialization.JSONObjectWithData(geocodingResultsData!, options:
NSJSONReadingOptions.MutableContainers, error: &error) as!
Dictionary<NSObject, AnyObject>
以下全部功能:
func geocodeAddress(address: String!, withCompletionHandler completionHandler: ((status: String, success: Bool) -> Void)) {
if let lookupAddress = address {
var geocodeURLString = baseURLGeocode + "address=" + lookupAddress
geocodeURLString = geocodeURLString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)!
let geocodeURL = NSURL(string: geocodeURLString)
dispatch_async(dispatch_get_main_queue(), { () -> Void in
let geocodingResultsData = NSData(contentsOfURL: geocodeURL!)
var error: NSError?
let dictionary: Dictionary<NSObject, AnyObject> = NSJSONSerialization.JSONObjectWithData(geocodingResultsData!, options: NSJSONReadingOptions.MutableContainers, error: &error) as! Dictionary<NSObject, AnyObject>
// let dictionary: Dictionary = NSJSONSerialization.JSONObjectWithData(geocodingResultsData!, options: NSJSONReadingOptions.MutableContainers, error: &error) as! Dictionary
if (error != nil) {
println(error)
completionHandler(status: "", success: false)
}
else {
// Get the response status.
let status = dictionary["status"] as! String
if status == "OK" {
let allResults = dictionary["results"] as! Array<Dictionary<NSObject, AnyObject>>
self.lookupAddressResults = allResults[0]
// Keep the most important values.
self.fetchedFormattedAddress = self.lookupAddressResults["formatted_address"] as! String
let geometry = self.lookupAddressResults["geometry"] as! Dictionary<NSObject, AnyObject>
self.fetchedAddressLongitude = ((geometry["location"] as! Dictionary<NSObject, AnyObject>)["lng"] as! NSNumber).doubleValue
self.fetchedAddressLatitude = ((geometry["location"] as! Dictionary<NSObject, AnyObject>)["lat"] as! NSNumber).doubleValue
completionHandler(status: status, success: true)
}
else {
completionHandler(status: status, success: false)
}
}
})
}
else {
completionHandler(status: "No valid address.", success: false)
}
}
答案 0 :(得分:0)
对于Swift 2,可以使用:
首先,将你的变量声明为do-catch块之外的空字典,并在块中进行赋值,如下所示
do {
dictionary = try NSJSONSerialization.JSONObjectWithData(geocodingResultsData!, options: NSJSONReadingOptions.MutableContainers) as! Dictionary<NSObject, AnyObject>
} catch {
//something
}