annaoomph
annaoomph

Reputation: 572

NSURLSession doesn't return data

I try to download a zip-archive using NSURLSessionDataTask. I am aware that there is a NSURLSessionDownloadTask, but the point is I want a didReceiveData callback (to show the progress).

The code is:

NSURLRequest *request = [NSURLRequest requestWithURL:@"..."
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];

NSURLSessionConfiguration* config = [NSURLSessionConfiguration defaultSessionConfiguration];
NSOperationQueue *myQueue = [NSOperationQueue new];
myQueue.underlyingQueue = dispatch_get_main_queue();

NSURLSession *session = [NSURLSession sessionWithConfiguration:config
delegate:self 
delegateQueue:myQueue];

NSURLSessionDataTask* task = [session dataTaskWithRequest:request
completionHandler:^( NSData *data, NSURLResponse *response, NSError *error){ ... }

[task resume];

My class conforms to NSURLSessionDataDelegate.

When I call the method, after several seconds debugger goes to completionHandler with nil data and nil error. What am I doing wrong?

I also tried:

Upvotes: 0

Views: 553

Answers (1)

annaoomph
annaoomph

Reputation: 572

So I have found the answer and it's not quite obvious from documentation: I had several callbacks, and among them didReceiveResponse.

Turns out I have to call completion handler in order for the future callbacks to work, i.e: completionHandler(NSURLSessionResponseAllow);

And one more thing: didCompleteWithError is actually the delegate that tells about successful finish, too, although the name implies that this is the error handler. What it means: when a download is successfully finished, this function is called with error = nil.

Hope this will be useful for somebody someday.

Upvotes: 1

Related Questions