
[英]How to get values of an array of dictionary from alamofire response using swift3
[英]How to save response.result.value from Alamofire in local array swift 3
Alamofire.request(NEWS_FEED_URL).responseJSON { response in
guard let newsResponse = response.result.value else{
print("Error: \(response.result.error)")
return
}
print("JSON: \(newsResponse)")
let localArray:Array = [newsResponse]
print("Local Array:", localArray)
}
I am using alamofire to fetch data from server and trying to write parser on the response data. When I fetch response.result.value from alamofire and print it is working fine. But as soon as I put response.result.value in my local array it gives
[<__NSArrayI 0x6080000bcf80>(
{
category = World;
})]
依此类推(控制台)。 此外,我无法将“Any”类型的响应值转换为“Array”。 请帮助我如何在“Array”类型的本地数组中添加 response.result.value。 有人可以简要解释一下在 alamofire 上进行类型转换吗?
您只需将response.result.value
的结果转换为字典数组。
guard let newsResponse = response.result.value as? [[String:String]] else{
print("Error: \(response.result.error)")
return
}
print("JSON: \(newsResponse)")
let localArray = newsResponse
//Access the localArray
print("Local Array:", localArray)
//Now to get the desired value from dictionary try like this way.
let dic = localArray[0]
let title = dic["title"] ?? "Default Title"
let link = dic["link"] as? "Default link"
//... get other value same way.
注意:您的响应已经是一个Array
,因此不要通过将其添加到另一个数组中来从中创建数组。
responseJOSN
结果有问题,因为结果可能不正确 JSON 格式以正确使用[[String:Any]]
格式化 JSON
Alamofire.request(NEWS_FEED_URL).responseJSON { response in
guard let newsResponse = response.result.value as? [[String:Any]] else{
print("Error: \(response.result.error)")
return
}
print("JSON: \(newsResponse)")
let firstRow = newResponse[0]
let categoryValue = firstRow["category"] ?? "Default Category"
}
如果您使用的是可解码技术,则可以将响应中的数据保存在用户默认设置中。 用户默认值允许我们保存数据。 当你需要它时,你可以使用 JSON 解码器来解码 JSON 数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.