尝试构建一个 iOS 应用程序,它将找到最近的餐厅并将其放置在谷歌地图上。但无法读取 JSON 文件。
var coordinate = [AnyObject]()
Alamofire.request(key).responseJSON { (response) in
let data = response.result
if let json = data.value as? Dictionary<String,AnyObject>{
if let results = json["results"]
{
if let geometry = results["geometry"] as? Dictionary<String,AnyObject>
{
if let location = geometry["location"]
{
self.coordinate = location as! [AnyObject]
}
}
}
}
}
当我将结果放入数组中时,它会被存储,但上面的代码不起作用。我想从 JSON 文件中读取几何图形。该怎么办 下面是JSON文件格式
{
html_attributions: [ ],
next_page_token: "CrQCIwEAAD1hVtsv2Rq1gXGAFL67ucrXNKqh-2Km4rUSgkPUYZA4apoWTxWmUgVKX9tYTyOkHRtfU6hJsu7QBq1fZNDWB-bAcryr8ADW4bBfszYCIDkg9F2JBrxn2iMFYspvx0aQSyblSD3EoYP2qmjD4itG_pCC67Eo_Pk1Xcsoxx4ZW5O9wvtrby7WNPOUGnIlSBOZ4R-5tjwkOEZCcroM3lBjF1fQbrZ7F-2_ymgf-h3C1sdW4iV4AG85rgIcWeeAW_uwamnyvChTSqSjf_q4IiqNoA9T-q4ZmZGXgkIOk2omzjqEm1Q563RRjGXSrRV8kTeF4t_S-Xeq4-05SRwe3Gx-3t9KBDXR9W9nRH8W08H08wrBYs0O239HUXLbgGLgmZr6h8n4YQbJETLCwI_QTCtOh3sSEMCf6iNSUBjd76aHUHN1b6YaFHTkB0-5Yh8szipA_BLiVYIE0ebm",
results: [
{
geometry: {
location: {
lat: 51.51021369999999,
lng: -0.1315736
},
viewport: {
northeast: {
lat: 51.51158128029149,
lng: -0.130123169708498
},
southwest: {
lat: 51.5088833197085,
lng: -0.132821130291502
}
}
},
icon: "https://maps.gstatic.com/mapfiles/place_api/icons/lodging-
71.png",
id: "b501c78eff5bb3e4b7f67dfe97727cec52a693c5",
name: "Thistle Piccadilly Hotel",
photos: [
{
height: 337,
html_attributions: [
"<a href="https://maps.google.com/maps/contrib/110195987647911662808/photos">Thistle Piccadilly Hotel</a>"
],
photo_reference: "CmRaAAAA5ohge6XYb1kjWk5C_KJdzFRx3SBF9QjkZUgUQ36av_eSP-9sjkvwncvOk5gPvVeC_Tgj4lcYr0DDm-x3JxMvnLMykI7BzAJAdoYs2VKeGNPWxX0VKdH2m72PSUScH_f4EhBJqRr0iXUwsO-IQHO2TWPGGhS8mbZaVg5BaJLnGAtE6t-cyi2naA",
width: 338
}
],
place_id: "ChIJZewrLtIEdkgRtl2nZKboAgk",
plus_code: {
compound_code: "GV69+39 St. James's, London, United Kingdom",
global_code: "9C3XGV69+39"
},
rating: 4.4,
reference: "ChIJZewrLtIEdkgRtl2nZKboAgk",
scope: "GOOGLE",
types: [
"bar",
"lodging",
"restaurant",
"point_of_interest",
"food",
"establishment"
],
vicinity: "Coventry Street, London"
}
],
status: "OK"
}
如何从上述 JSON 文件中读取纬度和经度。
最佳答案
首先,Swift 3+ 中的 JSON 值绝不是 AnyObject
,而是 Any
名称 results
暗示了这一点,并且 JSON 证明了这一点 - 请注意 []
- 该值是一个数组,而不是字典
import CoreLocation
typealias JSONDictionary = [String:Any]
var coordinates = [CLLocationCoordinate2D]()
Alamofire.request(key).responseJSON { (response) in
if let json = response.result.value as? JSONDictionary,
let results = json["results"] as? [JSONDictionary] {
for result in results {
if let geometry = results["geometry"] as? JSONDictionary,
let location = geometry["location"] as? JSONDictionary {
coordinates.append(CLLocationCoordinate2D(latitude: location["lat"] as! Double, longitude: location["lng"] as! Double))
}
}
}
}
关于iphone - Alamofire 无法读取 JSON 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53790345/