gpt4 book ai didi

ios - GooglePlaces API Swift 3 问题

转载 作者:行者123 更新时间:2023-11-28 16:07:47 25 4
gpt4 key购买 nike

自从更新到 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 并导致崩溃。

我不明白为什么它返回零。我可以将 url 中的 correctedAddress 替换为值 %51%75%C3%A9%62%65%63%2C%20%43%61%6E%61%64%61 所以完整的 url 是

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") 并且工作正常。

问题#2:它在 let results 处崩溃,我返回错误 Could not cast value of type '__NSArrayI' (0x108bb0c08) to 'NSDictionary' (0x108bb1108).

最佳答案

针对您的问题 #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)!

关于ios - GooglePlaces API Swift 3 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39995402/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com