[英]iOS Swift - Instagram API get response from WebView NSURL Request
[英]How to get array response in swift iOS Request
我发送这样的请求:
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {
// check for fundamental networking error
print("error=\(String(describing: error))")
completion(nil)
return
}
print("********_Respone status code is: ",(response as! HTTPURLResponse).statusCode)
print("********_Respone url code is: ",response?.url as Any )
do {
let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [String: Any]
let res:HTTPURLResponse = response as! HTTPURLResponse
print(json)// yessssssssss goooood
} catch {
completion(nil)
return
}
}
task.resume()
当响应是字典时它可以正常工作,但是当我的响应是数组时显示此错误:
无法将“__NSArrayI”类型的值转换为“NSDictionary”
请帮我解决这个问题。
将 JSON 反序列化一次并省略选项, Array
和Dictionary
are not fragmented 。 然后可选绑定结果。
do {
let json = try JSONSerialization.jsonObject(with: data)
if let jsonArray = json as? [[String:Any]] {
print("json is array", jsonArray)
} else if let jsonDictionary = json as? [String:Any] {
print("json is dictionary", jsonDictionary)
} else {
print("This should never be displayed")
}
} ...
如果结果应该只是数组或字典,那么您可以强制将结果解包到字典并删除最后一个else
子句
do {
let json = try JSONSerialization.jsonObject(with: data)
if let jsonArray = json as? [[String:Any]] {
print("json is array", jsonArray)
} else {
let jsonDictionary = json as! [String:Any]
}
} ...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.