【发布时间】:2018-01-03 12:42:45
【问题描述】:
我在 Xcode 上使用 Swift 并尝试解析 JSON 文件以检索有关附近商店的一些数据。 我的源代码如下:
import GooglePlaces
import SwiftyJSON
class Place {
let name: String
let coordinates: CLLocationCoordinate2D
init(diction:[String : Any])
{
let json = JSON(diction)
name = json["name"].stringValue //as! String
let lat = json["geometry"]["location"]["lat"].doubleValue as CLLocationDegrees
let long = json["geometry"]["location"]["lng"].doubleValue as CLLocationDegrees
coordinates = CLLocationCoordinate2DMake(lat, long)
}
}
class ViewController: UIViewController, MKMapViewDelegate, SceneLocationViewDelegate {
var urlString = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?"
urlString += "&location=51.507514,-0.073603"
urlString += "&radius=1500" //meters
urlString += "&name=Specsavers"
urlString += "&key=**************************"
guard let url = URL(string: urlString) else {return}
var places = [Place]()
var request = URLRequest(url:url)
request.httpMethod = "GET"
let task = URLSession.shared.dataTask(with: request as URLRequest) {
data, response, error in
print("HEREurlSession")
if let content = data {
do {
let json = try JSONSerialization.jsonObject(with: content, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject
print(json) // json results are printed fine here
if let results = json["results"] as? [[String : Any]] {
for place in results {
places.append(Place(diction: place))
}
}
else {
print("return")
}
}
catch{
}
}
}
task.resume()
let size = places.count
print("HERE: ", size)
}
构建成功但输出为size = 0,这意味着我没有检索数据并且变量places 为空。
我不知道它是否完全相关,但我收到以下警告:Cast from 'MDLMaterialProperty?!' to unrelated type '[[String : Any]]' always fails for the line if let results = json["results"] as? [[String : Any]] in my source code。
为什么我没有正确解析 JSON 文件,也没有检索到我想要的数据?
【问题讨论】:
-
不相关,但为什么要将
URLRequest转换为URLRequest?这是没有意义的。顺便说一下,GET请求根本不需要URLRequest。为什么将mutableContainers分配给不可变常量?这也没有意义 -
感谢您的回复。几周后我现在再次捕获此源代码,我不记得从哪里开始,但我确信 SO 中的一个好的教程或一个好的答案建议这样做。从这个意义上说,我认为这不是问题,但如果您坚持这样做,请告诉我。
-
当然不是问题,这就是我写unrelated的原因。发布 JSON 响应的相关部分会很有帮助。警告显示
results的值不是[[String : Any]]。并且代码末尾的places.count == 0是正确的,因为dataTask是异步工作的。 -
我建议您使用 Alamofire 来处理您的网络请求,它会简化您的生活。还有新的 Codable 协议而不是 SwiftyJSON。
-
感谢您的回复和建议。我会记住的。
标签: json swift google-places-api