我正在做一个JSON请求,我在整个应用程序中做了同样的事情。但不知何故,在这种特殊情况下,它根本没有任何错误。
这就是我调用JSON的方式,我放置了应该在控制台中显示的2 prints
。第一个做,第二个做任务。
let url = URL(string: "http://api.openweathermap.org/data/2.5/forecast/daily?q=\(cityName),PL&mode=json&units=metric&cnt=5&appid=e9f269***")
var request = NSMutableURLRequest(url: url! as URL, cachePolicy: NSURLRequest.CachePolicy.returnCacheDataElseLoad, timeoutInterval: Double.infinity)
if Reachability.isConnectedToNetwork(){
request = NSMutableURLRequest(url: url! as URL, cachePolicy: NSURLRequest.CachePolicy.useProtocolCachePolicy, timeoutInterval: Double.infinity);
}
let session = URLSession.shared
print("This does get returned in the console")
let task = session.dataTask(with: request as URLRequest,
completionHandler: { data, response, error -> Void in
do {
if let json = try JSONSerialization.jsonObject(with: data!) as? [[String: String]] {
print("This is not returned in the console")
for weerData in json {
self.weerItemsDag.append(DailyWeatherItem(dictionary:weerData as NSDictionary)!)
}
//Retrieved JSON
//Get daily weather items
self.getDailyWeatherItems(cityName: cityName)
}
} catch { print(error) }
})
task.resume()
示例JSON:
{
"city":{
"id":3099434,
"name":"Gdansk",
"coord":{
"lon":18.6464,
"lat":54.3521
},
"country":"PL",
"population":461865
},
"cod":"200",
"message":0.516424,
"cnt":5,
"list":[
{
"dt":1515146400,
"temp":{
"day":5,
"min":4.38,
"max":5.21,
"night":4.5,
"eve":4.91,
"morn":5
},
"pressure":997.38,
"humidity":96,
"weather":[
{
"id":500,
"main":"Rain",
"description":"light rain",
"icon":"10d"
}
],
"speed":10.02,
"deg":246,
"clouds":64,
"rain":1.27
},
{
"dt":1515232800,
"temp":{
"day":4.45,
"min":3.19,
"max":4.83,
"night":3.19,
"eve":4.68,
"morn":4.05
},
"pressure":1012.94,
"humidity":100,
"weather":[
{
"id":800,
"main":"Clear",
"description":"sky is clear",
"icon":"01d"
}
],
"speed":5.9,
"deg":271,
"clouds":88,
"rain":0.69
},
{
"dt":1515319200,
"temp":{
"day":2.18,
"min":1.06,
"max":2.5,
"night":1.62,
"eve":1.71,
"morn":1.73
},
"pressure":1034.07,
"humidity":100,
"weather":[
{
"id":800,
"main":"Clear",
"description":"sky is clear",
"icon":"01d"
}
],
"speed":5.71,
"deg":331,
"clouds":0
},
{
"dt":1515405600,
"temp":{
"day":2.57,
"min":0.8,
"max":3.94,
"night":0.84,
"eve":2.04,
"morn":3.94
},
"pressure":1043.75,
"humidity":97,
"weather":[
{
"id":800,
"main":"Clear",
"description":"sky is clear",
"icon":"01d"
}
],
"speed":4.45,
"deg":341,
"clouds":0,
"snow":0.01
},
{
"dt":1515492000,
"temp":{
"day":1.52,
"min":-2.57,
"max":1.52,
"night":0.3,
"eve":-0.6,
"morn":-2.57
},
"pressure":1037.52,
"humidity":0,
"weather":[
{
"id":800,
"main":"Clear",
"description":"sky is clear",
"icon":"01d"
}
],
"speed":3.36,
"deg":280,
"clouds":0,
"snow":0.02
}
]
}
答案 0 :(得分:1)
请阅读JSON,{}
是字典,[]
是数组,所以根对象显然是字典
if let json = try JSONSerialization.jsonObject(with: data!) as? [String: Any],
let list = json["list"] as? [[String:Any]] {
for weerData in list {
...
JSON中根本没有[[String:String]]
数组。
并且不要在Swift中使用NSDictionary
和NS(Mutable)URLRequest