我正在尝试发布http帖子请求, 但是该方法在字典填充之前返回。
如何强制方法等待回调?
func makeRequest()-> [String :AnyObject]{
var ans : [String :AnyObject] = ["response" : "", "data" : "", "error" : ""]
var request = NSMutableURLRequest(URL: NSURL(string: self.url)!, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData, timeoutInterval: 5)
if self.jsonIcluded {
var err: NSError?
let req = NSJSONSerialization.dataWithJSONObject(self.data!, options: NSJSONWritingOptions.PrettyPrinted, error: &err)
request.HTTPBody = req
}
request.HTTPMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
if error != nil
{
println("error=\(error)")
return
}
ans["response"] = response
ans["data"] = data
ans["error"] = error
}
task.resume()
return ans
}
答案 0 :(得分:0)
NSURLSession用于发出异步请求。如果要发送同步请求,请使用NSURLConnection -sendSynchronousRequest:
方法。
let reply = NSURLConnection.sendSynchronousRequest(request, returningResponse:&response, error:&error)
return reply