0

When i call this function , function returns value and then doing all other things. How can i make function to return value end of other things.

    func register(parameters : [String : String]) -> Int {

    let headers = [
        "content-type": "application/json",
        "cache-control": "no-cache",
    ]
    var statuscode = 0
    var postD = NSData();
    do {
        let postData = try NSJSONSerialization.dataWithJSONObject(parameters, options: NSJSONWritingOptions.PrettyPrinted)
        postD = postData;
    }catch let error as NSError{
        print(error.description)
    }
    var request = NSMutableURLRequest(URL: NSURL(string: "\(hostUrl)/users")!,
                                      cachePolicy: .UseProtocolCachePolicy,
                                      timeoutInterval: 10.0)

    request.HTTPMethod = "POST"
    request.allHTTPHeaderFields = headers
    request.HTTPBody = postD

    let session = NSURLSession.sharedSession()
    let dataTask = session.dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in
        if (error != nil) {
            print(error)
        } else {
            let httpResponse = response as? NSHTTPURLResponse
            statuscode = httpResponse!.statusCode
            print("AFTER HTTP RESPONSE STATUSCODE = \(statuscode)")

        }
    })

    dataTask.resume()
    return statuscode
}

Im calling this function like this :

let statuscode = client.register(parameters)
        print("denemeeeeeeeeeeeeee\(statuscode)")

And this is my output

denemeeeeeeeeeeeeee0
AFTER HTTP RESPONSE STATUSCODE = 400

2 Answers2

1

NSURLSession is an asynchronous API, so I'm afraid your function will always return before the data request completes. You'll have to consider alternative approaches. For example your register method could receive a completion closure that you call when your data task is complete.

Craig Grummitt
  • 2,945
  • 1
  • 22
  • 34
0

You need to implement a callback function to handle this kind of stuff:

func register(parameters : [String : String], callback: ((success: Bool, response: NSHTTPURLResponse)->Void){

let headers = [
    "content-type": "application/json",
    "cache-control": "no-cache",
]
var postD = NSData();
do {
    let postData = try NSJSONSerialization.dataWithJSONObject(parameters, options: NSJSONWritingOptions.PrettyPrinted)
    postD = postData;
}catch let error as NSError{
    print(error.description)
}
var request = NSMutableURLRequest(URL: NSURL(string: "\(hostUrl)/users")!,
                                  cachePolicy: .UseProtocolCachePolicy,
                                  timeoutInterval: 10.0)

request.HTTPMethod = "POST"
request.allHTTPHeaderFields = headers
request.HTTPBody = postD

let session = NSURLSession.sharedSession()
let dataTask = session.dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in
    if (error != nil) {
        print(error)
    } else {

        let httpResponse = response as? NSHTTPURLResponse
        callback?(success: true, response: httpResponse)


    }
})

dataTask.resume()
}

and in your function call:

client.register(parameters, callback: { (success, response) in
     var statuscode = 0
     statuscode = response!.statusCode
     print("AFTER HTTP RESPONSE STATUSCODE = \(statuscode)")
})

If this is not enough to achieve what you want to do, you could also look into dispatch groups.

Best of luck.

Community
  • 1
  • 1
Geoherna
  • 3,523
  • 1
  • 24
  • 39