swift alamofire请求json异步

问题描述 投票:0回答:2

我试图通过Alamofire发送一个从亚马逊获取JSON的请求,但它是异步的。它在从亚马逊获得响应之前返回到调用者函数。

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"])
}

myJson函数中的对象initTableView总是为零。

我该如何解决这个问题?

ios swift asynchronous alamofire
2个回答
0
投票

而不是返回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)
}

要么:

getJSON(fileName: "/jsonsBucket/myJson.json", completion: { json in
    print(json)
})

0
投票

你需要实现一个完成处理程序,看看这个article

完成处理程序是我们提供的代码,当它返回这些项时被调用。这是我们可以处理调用结果的地方:错误检查,在本地保存数据,更新UI等等。

typealias completionHandler = (JSON?) -> Void // this is your completion handler

public func getJSON(fileName: String, completionHandler: @escaping completionHandler) -> JSON?{
    let url = "http://s3.eu-west-3.amazonaws.com" + fileName
    if self.json == nil {
        Alamofire.request(url)
            .responseJSON { response in
                if let result = response.result.value {
                  completionHandler(json) // this will fire up your completion handler,
                }
        }
    }
    else{
        completionHandler(nil)
    }
}

你可以像这样使用它。

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)
}
© www.soinside.com 2019 - 2024. All rights reserved.