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

余生颓废 提交于 2019-12-11 12:21:42

问题


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.


回答1:


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 {

}


来源:https://stackoverflow.com/questions/24857919/how-can-i-receive-my-data-in-pieces-with-using-nsurlconnections-sendasynchronou

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!