1

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.

Tyler Pfaff
  • 4,900
  • 9
  • 47
  • 62

1 Answers1

0

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 {

}
Yatheesha
  • 10,412
  • 5
  • 42
  • 45
  • Ignore my previous comment, my connection dies when the view controller it is launched in is dismissed. What can I do? – Tyler Pfaff Jul 21 '14 at 16:39
  • Its better to make a shared object which always keep track of you download data till app is running irrespective of view controller. – Yatheesha Jul 21 '14 at 18:41