简体   繁体   中英

How to Cancel all NSURLConnections in Background in iOS

I am downloading some Images (approx 200-300 thumb images) on Using NSURLCOnnections. I have array of urls of these images. The connection starts to download these images. But in certain case i want to cancel all these downloading. How it is possible. Can i cancel all these NSURLConnections.

Will be better to create NSOperationQueue and work with NSURLConnection through this queue.

For example:

NSOperationQueue *queue = [NSOperationQueue new];
NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(sendRequest)];


- (void) sendRequest {
    NSURL *url = [NSURL URLWithString:@"http://www.google.com"];
    NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
    NSURLConnection *theConnection = [[[NSURLConnection alloc] initWithRequest:theRequest delegate:self] autorelease];
    ...
}

NSOperationQueue has method cancelAllOperations

[connection cancel]用于取消NSURLConnection。

I would use a synchronous NSURLConnection in combination with an NSOperationQueue to download the data:

[queue addOperationWithBlock:^{
    NSData *data = [NSURLConnection
        sendSynchronousRequest:…
        returningResponse:… error:…];
}];

This way you can easily control the number of concurrent downloads and cancel the unfinished ones using [queue cancelAllOperations] . Note that cancelling the queue won't stop the downloads that have already started, but that won't be a problem if you're downloading just small thumbnails and have a decent concurrent download limit.

Synchronous NSURLConnection mode has the advantage of being much easier to use than the asynchronous delegation API.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM