Search code examples
iosswiftnsurlconnectionnsurlsession

Swift NSURLSession really really really slow


I am using NSURLSession in my app like so:

func wsQAshowTag(tag: Int, completion: ([AnyObject]! -> Void)) {
        let requestString = NSString(format: “URL”, tag) as String
        let url: NSURL! = NSURL(string: requestString)
        let task = NSURLSession.sharedSession().dataTaskWithURL(url, completionHandler: {
            data, response, error in
            do {
                let result = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as! [AnyObject]
                completion(result)
            }
            catch {
                completion(nil)
            }
        })
        task.resume()
    }

This works as expected, however I am finding it very very slow, when I was using NSURLConnection I found it extremely fast (this is with the same URL) How come NSURLSession is very slow when NSURLConnection is very fast? and is there away to speed up NSURLSession?

Here is how I am calling it:

self.wsQAshowTag(Int(barcode)!, completion: { wsQAshowTagArray in
     //Code Here
})

Solution

  • You need to send UI updates to the main queue. If you update it without sending it to the main queue it can take a very long time to update data.

    You also need to wrap completion(result) since we're parsing JSON.

    The code grabs the stored completion handler and invokes it on the main thread.

    func wsQAshowTag(tag: Int, completion: ([AnyObject]! -> Void)) {
    let requestString = NSString(format: "URL", tag) as String
    let url: NSURL! = NSURL(string: requestString)
    let task = NSURLSession.sharedSession().dataTaskWithURL(url, completionHandler: {
        data, response, error in
        do {
            let result = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments) as! [AnyObject]
            dispatch_async(dispatch_get_main_queue()) {
                completion(result)
            }
        } catch {
            dispatch_async(dispatch_get_main_queue()) {
            completion(nil)
            }
            print("error serializing JSON: \(error)")
        }
    })
    task.resume()
    }