Ios swift alamofire请求json异步
我试图通过Alamofire发送一个请求,从Amazon获取JSON,但它是异步的。在从Amazon获得响应之前,它返回到调用方函数Ios swift alamofire请求json异步,ios,swift,asynchronous,alamofire,Ios,Swift,Asynchronous,Alamofire,我试图通过Alamofire发送一个请求,从Amazon获取JSON,但它是异步的。在从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.reque
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"])
}
initTableView
函数中的对象myJson
始终为nil
如何解决此问题?而不是返回JSON?在方法签名中,使用如下完成闭包:
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)
}
}
}
getJSON(fileName: "/jsonsBucket/myJson.json") { json in
print(json)
}
并按如下方式调用该方法:
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)
}
}
}
getJSON(fileName: "/jsonsBucket/myJson.json") { json in
print(json)
}
或:
您需要实现一个完成处理程序, 看看这个 完成处理程序是我们提供的代码,当它与这些项目一起返回时被调用。在这里,我们可以处理调用的结果:错误检查、本地保存数据、更新UI等等 你可以这样使用它
getJSON(fileName: "fileName") { (json) in
// this will fire up when completionhandler clousre in the function get triggered
//then you can use the result you passed whether its JSON or nil
guard let result = json else { return } // unwrap your result and use it
print(result)
}