I’m trying to migrate to NSURLSession
from NSURLConnection
. I’ve used delegate methods to return the JSON object IN NSURLConnection
previously. But now I’m looking to implement blocks to return the JSON object. I have my own block to return the JSON object since I have NSURLSession
Network Aactivity in a separate class common to all service calls. I ahve use its delegate methods and everything is working fine but when I use its in-built block to get the object and return it using my own block thats when things get messy.
I've searched through web and found people using GCD to get the mainqueue and invoking the return block. I tried that too but sometimes it gets delayed too. What is the best practice to do this?
Here's my code
let urlString = baseURL + methodName
let postString = NSString(bytes: postData.bytes, length: postData.length, encoding: NSUTF8StringEncoding)
let request : NSMutableURLRequest = NSMutableURLRequest(URL: url)
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.HTTPMethod = "POST"
request.HTTPBody = postString?.dataUsingEncoding(NSUTF8StringEncoding)
request.timeoutInterval = requestTimeOutInterval
let task = NSURLSession.sharedSession().dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
NSURLSession.sharedSession().finishTasksAndInvalidate()
do {
let responseDict: NSMutableDictionary? = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as? NSMutableDictionary
dispatch_async(dispatch_get_main_queue()) {
completionHandler(responseDict, nil, true)
}
} catch let err as NSError {
dispatch_async(dispatch_get_main_queue()) {
completionHandler(nil, nil, true)
}
}
})
task.resume()