我有一个函数可以将字典发回服务器,并在出现错误时返回状态代码或错误内容。它有时候工作正常,而其余时间则跳过完成部分。
func postData(url: String, query: NSDictionary) ->NSObject? {
var error: NSError?
var result: NSObject? = nil
let dest = NSURL("http://myUrl.com")
let request = NSMutableURLRequest(URL: dest!)
request.HTTPMethod = "POST"
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(query, options: NSJSONWritingOptions.allZeros, error: &err)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
let task = NSURLSession.sharedSession().dataTaskWithRequest(request){
data, response, error in
if(error != nil){
println(error)
result = error
return
}
result = (response as! NSHTTPURLResponse).statusCode
return
}
task.resume()
return result
}
我提到了NSURLSession dataTaskWithRequest not being called,并且知道它可能是由于执行时滞造成的。但是,由于我需要状态代码(到目前为止返回nil)来确定发布后要执行的操作,我想知道如何解决这个问题?
答案 0 :(得分:5)
你的方法是异步方法,你无法从中获得回报。
您可以通过返回
传入一个块来处理您的操作func postData(url: String, query: NSDictionary,finished:(NSObject)->()) {
var error: NSError?
var result: NSObject? = nil
let dest = NSURL("http://myUrl.com")
let request = NSMutableURLRequest(URL: dest!)
request.HTTPMethod = "POST"
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(query, options: NSJSONWritingOptions.allZeros, error: &err)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
let task = NSURLSession.sharedSession().dataTaskWithRequest(request){
data, response, error in
if(error != nil){
println(error)
result = error
return
}
finished((response as! NSHTTPURLResponse).statusCode)
}
task.resume()
}
然后使用它
postData(url, dic) { (object:NSObject) -> () in{
//use here
}