0

I have written two following functions for using NSURLSession.

func getStringFromRequest(completionHandler:(success:Bool, data: NSData?) -> Void) {

    let prefs = NSUserDefaults.standardUserDefaults()
    var conn_timeout = prefs.stringForKey("conn_timeout")!

    var IP = prefs.stringForKey("IP")!
    var port = prefs.stringForKey("Port")!
    prefs.synchronize()

    var request = NSMutableURLRequest(URL: NSURL(string: "http://\(IP):\(port)/")!)
    var response: NSURLResponse?
    var error: NSError?

    var jsonString = ["osname":"iOS","mobile_manufacturer" : "Apple","mobile_model" : "iPhone Simulator","osversion" : "8.4"]  as Dictionary<String, String>

    request.HTTPBody = NSJSONSerialization.dataWithJSONObject(jsonString, options: nil, error: &error)
    request.HTTPMethod = "POST"
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")
    request.setValue("gzip", forHTTPHeaderField: "Accept-encoding")

    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { (data, response, error) -> Void in

        if let unwrappedError = error {
            print("error=\(unwrappedError)")
        }
        else {
            if let unwrappedData = data {
                completionHandler(success: true, data: unwrappedData)
                return
            }
        }

        completionHandler(success: false, data: nil)
    }

    task.resume()
}

func performPost() -> NSDictionary {
    var result = NSDictionary()

    getStringFromRequest { (success, data) -> Void in

        if (success) {

            if let unwrappedData = data {

                if let responseString = NSString(data: unwrappedData, encoding: NSUTF8StringEncoding) {
                    println("------------------>>>>>>NSURLSession>>>>>>>-------------------------->\n: \(responseString)")
                    result = (NSJSONSerialization.JSONObjectWithData(unwrappedData, options: NSJSONReadingOptions.allZeros, error: nil) as? NSDictionary)!

                }
            }
        }
        else {
            print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>Failed>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>")
        }
    }
}

I am calling the performPost function as follows:

self.connectionHelper.performPost()
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), { ()->() in
    println("self.connectionHelper.result>>>>>>========================================>>>>>>>  :  \(self.connectionHelper.result)!")
})

Output is as follow:

self.connectionHelper.result>>>>>>========================================>>>>>>>  :  {
}!

------------------>>>>>>NSURLSession>>>>>>>-------------------------->

After looking at the output of the performPost function I can say that the execution to the pritln function first but it is called later than performPost.

How can I set the value of result first in the performPost function then prints its value after completion of the performPost function.

Can it be possible?

Amit Raj
  • 1,358
  • 3
  • 22
  • 47

1 Answers1

1

Instead of calling dispatch_async to print the results, pass a completion handler block to your performPost method, and print the results in that completion handler block.

dgatwood
  • 10,129
  • 1
  • 28
  • 49