我有一个类方法,这个方法需要一些时间从一个http请求中获取数据。
方法的相关部分:
do{
request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(params, options: NSJSONWritingOptions())
} catch {
print("Cound not serilize")
}
let task = session.dataTaskWithRequest(request) {
data, response, error in
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions()) as? NSDictionary
self.result = json! as? [String : AnyObject]
print(self.result)它将从JSON中打印正确的结果,但在另一边,对象实例authGuestAPI不会:
let authGuestAPI = API(url: apiUrl, params: params, method: "POST")
authGuestAPI.run()
print("RESULT: \(authGuestAPI.result)")它将打印“结果:零”。
但是如果我把NSThread.sleepForTimeInterval(2)放在print("RESULT: \(authGuestAPI.result)")之前,它就会打印正确的json数据。
发布于 2016-04-24 10:18:15
我使用SwiftyJSON和Alamofire与completionHandler一起制作下载方法来解决这个问题。
func download(completionHandler: (JSON?, NSError?) -> ()) -> (){
Alamofire.request(.POST, url, parameters: self.params, encoding: ParameterEncoding.URLEncodedInURL , headers: self.header).responseJSON { (result: Response<AnyObject, NSError>) -> Void in
if result.result.isSuccess {
self.hasError = false
self.result = JSON(result.result.value!)
} else if result.result.isFailure {
self.errorCode = result.result.error!.code
self.errorMessage = result.result.error!.localizedDescription
print(result.result.error?.localizedDescription)
self.hasError = true
}
completionHandler(self.result, result.result.error)
}
}发布于 2016-03-08 20:50:31
您需要在调用api请求时创建一个函数。然后用该函数实现一个完成处理程序。在最终从api返回值时,将希望执行的代码添加到完成处理程序中。
https://stackoverflow.com/questions/35877603
复制相似问题