0

How can I return just a NSHttpUrlResponse status code from NSUrlSession. I am very new to this language.So,If there is other better practice please let me know.My code is right below here.

//Method to return a status code
        func responseCode() -> Int{
        var responseCode : Int=0
        if Reachability.isConnectedToNetwork() == true {
        // get news feed url
        let url = NSURL(string: baseUrl)
        let session = NSURLSession.sharedSession()
//create request
        let request = NSMutableURLRequest(URL: url!)
        request.HTTPMethod = httpMethod
//check null value
        if (bodyData != "") {
            request.HTTPBody =  bodyData.dataUsingEncoding(NSUTF8StringEncoding);
        }
        if (auth != "") {
            print("Token Auth : \(auth)")
            request.addValue("bearer \(self.auth)", forHTTPHeaderField:      "Authorization")
        }
        print("request : \(request)")

//How to return a Integer from this below function
        let task = session.dataTaskWithRequest(request,     completionHandler: {(data, response, error) -> Void in
            print("Error\(error)")
            if let httpResponse = response as? NSHTTPURLResponse {
                print("HttpReponse\(httpResponse.statusCode)")
                // Get a status code and assign it in a variable
                responseCode = httpResponse.statusCode
            }
        })
        task.resume()
//Return a response code in ViewController but it just return a initial set value that is 0
        return responseCode
        }
//Return a responseCode in ViewController but it just return a    initial set value that is 0
    return responseCode
    }
Vvk
  • 4,031
  • 29
  • 51
user3797004
  • 21
  • 1
  • 6
  • I have saw this previously but could not understand much because i am very new to this language. Can you please edit on my code. – user3797004 Feb 09 '16 at 10:07

1 Answers1

3

Here session.dataTaskWithRequest is an asynchronous task i.e. it will be called in another thread (other than the main thread) and its closure will be called when you get response from server.

So what you are doing here is you are trying to return responseCode which is called in main thread i.e. it will return before you have got any response.

You should use completion handler:

func responseCode(completion: (statusCode:Int) -> ()){
        if Reachability.isConnectedToNetwork() == true {

            let url = NSURL(string: baseUrl)
            let session = NSURLSession.sharedSession()

            let task = session.dataTaskWithRequest(request,completionHandler: {(data, response, error) -> Void in
                print("Error\(error)")

                if let httpResponse = response as? NSHTTPURLResponse {

                    print("HttpReponse\(httpResponse.statusCode)")
                    // Get a status code and assign it in a variable
                    completion(statusCode: httpResponse.statusCode)

                }
            })
            task.resume()
        }
    }

Use this function as below:

responseCode { (statusCode) -> () in
            print("Status Code:\(statusCode)")
    }
Hamza Ansari
  • 3,009
  • 1
  • 23
  • 25
  • I have called this function in this manner connection.responseCode({ statusCode -> Void in print("ResponseCode \(statusCode)") }) is this a right way because m not getting a value. – user3797004 Feb 09 '16 at 10:51
  • Have you set the `bodyData` and `auth` in your code because i removed some of your code just to focus on the `handler` – Hamza Ansari Feb 09 '16 at 10:57
  • Ya that thing i have done . even i have a print code at the top of the function even that print is not shown inside the log. – user3797004 Feb 09 '16 at 11:02
  • then you are not calling the function properly use breakpoints and check whether it's called or not – Hamza Ansari Feb 09 '16 at 11:06
  • Sorry, well i have not call this function inside view did load that's why the function is not returning a value.Thank you so much brother..thanks a lot once again.I wish i could vote u :) – user3797004 Feb 09 '16 at 11:09