自从更新到swift 3后,我似乎已经发现了一些错误
// Issue #1
let correctedAddress:String! = self.searchResults![(indexPath as NSIndexPath).row].addingPercentEncoding(withAllowedCharacters: CharacterSet.symbols)
print(correctedAddress)
let url = URL(string: "https://maps.googleapis.com/maps/api/geocode/json?address=\(correctedAddress)&sensor=false")
let task = URLSession.shared.dataTask(with: url!) {
data, response, error in
do {
if data != nil{
let dic = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableLeaves) as! NSDictionary
// Issue #2
let results = dic["results"] as! [String: Any]
let geometry = results["geometry"] as! [String: Any]
let location = geometry["location"] as! [String: Any]
let lat = location["lat"] as! Double
let lon = location["lng"] as! Double
self.delegate.locateWithLongitude(lon, andLatitude: lat)
}
}
catch {
print("Error")
}
}
task.resume()
问题#1:
例如,correctedAddress返回值"%51%75%C3%A9%62%65%63%2C%20%43%61%6E%61%64%61"
。然而,由于某种原因,url常量返回nil并导致崩溃。
我不明白为什么它会返回nil。我可以使用值correctedAddress
替换网址中的%51%75%C3%A9%62%65%63%2C%20%43%61%6E%61%64%61
,以便完整的网址
let url = NSURL(string: "https://maps.googleapis.com/maps/api/geocode/json?address=%51%75%C3%A9%62%65%63%2C%20%43%61%6E%61%64%61&sensor=false")
,它运作正常。
let results
崩溃,我得到了Could not cast value of type '__NSArrayI' (0x108bb0c08) to 'NSDictionary' (0x108bb1108).
的错误
答案 0 :(得分:1)
为问题#2
尝试以下代码let results = dic["results"] as! NSArray
for result in results {
let strObj = result as! NSDictionary
let geometry = strObj["geometry"] as! NSDictionary
let location = geometry["location"] as! NSDictionary
let lat = location["lat"] as! NSNumber
let lon = location["lng"] as! NSNumber
}
对于问题#1,请尝试以下代码
let valueAtIndex = self.searchResults![(indexPath as NSIndexPath).row].addingPercentEncoding(withAllowedCharacters: CharacterSet.symbols)
guard let correctedAddress = valueAtIndex else { return }
let adrString:String = "https://maps.googleapis.com/maps/api/geocode/json?address=\(correctedAddress)&sensor=false"
let url:URL = URL(string: adrString)!