首页 > 解决方案 > 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?

标签: iosswiftasynchronousalamofire

解决方案


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

推荐阅读