iosasynchronousnsurlconnectionnsurlconnectiondelegate

How can I receive my data in pieces with using NSURLConnection's sendAsynchronousRequest method?


When I send a synchronous request with NSURLConncetion

[NSURLConnection initWithRequest:myRequest delegate:self];

I can receive my downloaded data in pieces with the following method

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {

    [self.videoData appendData:data];
    NSLog(@"APPENDING DATA %@",data);

}

The advantage of this is that I can write my data directly to a file, and limit ram usage when downloading large files.

When I send an asynchronous request, how can I receive my data in pieces? The only place I see the data given back to me is in the completion handler of the request.

 [NSURLConnection sendAsynchronousRequest:videoRequest 
                                    queue:downloadQueue 
                        completionHandler:^(NSURLResponse* response, NSData* data, NSError* error){
        NSLog(@"All data is given here!");
    }];

Is there any solution to this problem? I'm downloading large files in a view controller and want to continue downloading them if the view controller gets dismissed. The problem is that I'm going to use too much memory if I receive all my data at once when downloading large files.


Solution

  • The only method in NSURLConnection which is synchronous is + sendSynchronousRequest:returningResponse:error:

    The following methods are all asynchronous

    + connectionWithRequest:delegate:
    – initWithRequest:delegate:
    – initWithRequest:delegate:startImmediately:
    + sendAsynchronousRequest:queue:completionHandler:
    – start
    

    So the code [NSURLConnection initWithRequest:myRequest delegate:self]; itself is an asynchronous, You can use it as it is.

    OR

    You can make use of NSURLSession for more control

    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
    
    self.downloadTask = [self.session downloadTaskWithRequest:request];
    [self.downloadTask resume];
    
    - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite {
    
    }