Swift dataTaskWithRequest completion block not executed

4.4k Views Asked by At

I have a function which posts a dictionary back to the server and return the status code or error content when there's an error. It works fine sometimes, while the rest of the time the completion section is skipped.

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
}

I referred to NSURLSession dataTaskWithRequest not being called, and knew that it may caused by executing time lag. However, since I need the status code (which returns nil so far) to determine the actions to do after the post, I'm wondering how I could solve this problem?

1

There are 1 best solutions below

1
On BEST ANSWER

Your method is async method,you can not get return from this.

You can pass in a block to handle your action with return

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

Then use it

postData(url, dic) { (object:NSObject) -> () in{
//use here
}