Alamofire 用的是 NSURLSession,而这货貌似本来就不能执行同步请求。。。好吧。。只能从想想其他办法了。。
恩。最后终于找到了一种解决方案,用semaphore
,代码大概如下:
public func XMresponseJSON(options options: NSJSONReadingOptions = .AllowFragments) -> Response<AnyObject, NSError> {
let semaphore = dispatch_semaphore_create(0)
var result: Response<AnyObject, NSError>!
self.responseJSON(queue: dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), options: options, completionHandler: {response in
result = response
dispatch_semaphore_signal(semaphore)
})
dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER)
return result
}
Usage
let resp = Alamofire.request(.POST, "\(Request_URl)/api/user/topicimg/upload/",parameters: ["token":"gb2h4ibp0i0g78gfgqjo63ei784l2qqg","image":image]).XMresponseJSON()
if resp.result.isSuccess{
success = true
print("9999999",success)
}
不过这样的话是不能在主线程(main_queue)中使用的,但是,大概应该也许不会有这种需求吧。。。
code:
https://github.com/Dalodd/Alamofire-Synchronous
转载:https://hran.me/archives/exec-synchronous-tasks-with-alamofire.html