Rasmus
Rasmus

Reputation: 241

Returning statusCode from NSHTTPURLResponse in a variable

I'm trying return the variable statusCode, which is supposed to take the value of the statusCode property of NSHTTPURLResponse, however I get zero, even when I check and I see that the data is successfully posted. It returns the 0 which I've initialized the variable with... how do I go about this? Thanks.

var statusCode = 0

let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
dispatch_async(queue) {
      let request = NSMutableURLRequest(URL: NSURL(string: escapedUrl!)!)
      request.HTTPMethod = "POST"
      let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
          data, response, error in

          if error != nil {
              statusCode = 0
          } else if let httpResponse = response as? NSHTTPURLResponse {
              if httpResponse.statusCode == 200 {
                  statusCode = httpResponse.statusCode
              } else {
                  statusCode = 0
              }
          }
      }
      task.resume()
  }
  return statusCode

}

Upvotes: 0

Views: 308

Answers (1)

Midhun MP
Midhun MP

Reputation: 107121

You are returning the statusCode before the asynchronous call returns the result. You can handle this case by passing a closure and calling it when the web-service returns the result. For that implement the method like:

func postData(escapedUrl : String?, onCompletion:(Int)->Void)
{
    let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
    dispatch_async(queue)
    {
        let request = NSMutableURLRequest(URL: NSURL(string: escapedUrl!)!)
        request.HTTPMethod = "POST"
        let task = NSURLSession.sharedSession().dataTaskWithRequest(request) 
        {
            data, response, error in

            var statusCode = 0

            if error != nil
            {
                statusCode = 0
            }
            else if let httpResponse = response as? NSHTTPURLResponse
            {
                if httpResponse.statusCode == 200
                {
                    statusCode = httpResponse.statusCode
                }
                else
                {
                    statusCode = 0
                }
            }
            // Passing back the result
            onCompletion(statusCode);
        }
        task.resume()
    }
}

You can call the method like:

postData("yourURLString") { (statusCode) -> Void in
    // Check status code here
}

Upvotes: 1

Related Questions