ios - swift alamofire request json asynchronous
问题描述
I tried to send a request to get a JSON from Amazon by Alamofire, but it asynchronized. it comes back to the caller function before getting the response from Amazon.
public func getJSON(fileName: String) -> JSON?{
let url = "http://s3.eu-west-3.amazonaws.com" + fileName
print(self.json)
if self.json == nil {
Alamofire.request(url)
.responseJSON { response in
if let result = response.result.value {
self.json = JSON(result)
}
}
return self.json
}
else{
return nil
}
}
public func initTableView(){
let myJson = AmazonFiles.shared.getJSON(fileName: "/jsonsBucket/myJson.json")
print(myJson["id"])
}
the object myJson
in initTableView
function is always nil.
How could I resolve this issue?
解决方案
Instead of returning JSON? in the method signature, use a completion closure like this:
public func getJSON(fileName: String, completion: ((JSON?) -> Void)?) {
let url = "http://s3.eu-west-3.amazonaws.com" + fileName
Alamofire.request(url).responseJSON { response in
if let result = response.result.value {
completion?(JSON(result))
} else {
completion?(nil)
}
}
}
And call the method like this:
getJSON(fileName: "/jsonsBucket/myJson.json") { json in
print(json)
}
Or:
getJSON(fileName: "/jsonsBucket/myJson.json", completion: { json in
print(json)
})
推荐阅读
- npm - VSCode 对 node_modules 没有智能感知
- python - Package Management - Pip / Conda / Virtualenv
- mule - Mulesoft Dataweave - 不能在“否则”子句中使用“使用”运算符中定义的变量
- postman - How to prettify JSON response that contains stringified JSON
- vb.net - VB.NET Using Trackbar to Re-Locate Text in Bitmap?
- python - Pandas 更改 Excel 的默认样式
- python - Matrix 在 Python 中给出了不同于 Matlab 中的其他规范值
- python-3.x - 字典作为函数范围内的全局变量
- c# - 在 C# 中使用 Apache Parquet 将 JSON 转换为 parquet 格式
- .net-core - 从完整的动态生成页面生成静态 HTML,.NET Core 3.1