如何取消[NSURLConnection sendAsynchronousRequest:..]发送的请求

时间:2015-06-27 12:39:45

标签: ios objective-c

我使用此代码发出请求:

- (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];
    }];
}

3 个答案:

答案 0 :(得分:2)

您可以声明

@property (nonatomic, strong) NSOperationQueue *downloadQ;

然后,

    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];
    }];

如果你需要停止

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

<强>更新

目前,最好使用NSURLSession,它有适当的方法:

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

然后检查task.originalRequest.URL以查找返回的任务以找到您要取消的任务。

答案 1 :(得分:1)

制作NSURLConnection的实例并调用其cancel函数。

答案 2 :(得分:0)

你可以使用。 声明

@property (nonatomic, strong) NSOperationQueue *downloadQ;
你的代码中的

-

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
      if (self.downloadQ)
    {
        [self.downloadQ cancelAllOperations];
    }

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

    [NSURLConnection sendAsynchronousRequest:request queue:self.downloadQ
                           completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {

           //write your code hare
     }];
}