Sanjay Changani Sanjay Changani - 3 months ago 44
Objective-C Question

How to cancel request sent by [NSURLConnection sendAsynchronousRequest:..]

I make a request with this code :

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
// Here I want to cancel Request , Request Url contains searchBar Texts
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
NSXMLParser *p = [[NSXMLParser alloc] initWithData:reqData];
[p setDelegate:self];
[p parse];
}];
}

Answer

You can declare

@property (nonatomic, strong) NSOperationQueue *downloadQ;

then,

    self.downloadQ = [NSOperationQueue new];
    self.downloadQ.name = @"download";

    [NSURLConnection sendAsynchronousRequest:request queue:self.downloadQ completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        NSXMLParser *p = [[NSXMLParser alloc] initWithData:reqData];
        [p setDelegate:self];
        [p parse];
    }];

If you need to stop

NSOperation *lastOp = [self.downloadQ.operations lastObject];
    [lastOp cancel];

UPDATE:

For now, it's better to use NSURLSession, which has the proper method for this:

- (void)getTasksWithCompletionHandler:(void (^)(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks))completionHandler;

Then check task.originalRequest.URL for returned tasks to find the one you want to cancel.