Posts in nsurlsession

  • NSURLSession delegateQueue Silently Fails if Passed The Main Queue

    Of important note: If you want your callbacks to come on the main queue, you
    cannot create an NSURLSession with
    sessionWithConfiguration:delegate:delegateQueue: and pass
    [NSOperationQueue mainQueue] as the delegateQueue argument. All requests
    will silently fail, and never return if you do.

    Instead you must continue to us dispatch_async(dispatch_get_main_queue(), ...) or [[NSOperationQueue mainQueue] addOperationWithBlock:...].

  • Asynchronous Networking with NSURLSession

    iOS 7 introduces an entire new networking stack for developers,
    NSURLSession. Generally it makes the common tasks simple, and the hard
    tasks possible. It also drives the new background fetch capabilities as well.

    Like my earlier post, offloading your networking from the main
    thread is a simple way to help keep an app responsive. Doing this with
    NSURLSession is actually quite easy.

    {% highlight objc %}
    NSURL *url = [NSURL urlWithString:@""];
    NSURLSessionTask *task = [[NSURLSession sharedSession] dataTaskWithURL:url
    ^(NSData *data, NSURLResponse *response, NSError *error) {
    if (data) {
    // Do stuff with the data
    } else {
    NSLog(@"Failed to fetch %@: %@", url, error);
    [task resume];
    {% endhighlight %}

    This will run the networking off of the main thread, and the callback will come from a system network queue. Generally this is what we want. If you want to have control over what queue the callback comes from, or to be able to handle authentication requests, you should create your own NSURLSession and delegate.