在ios中取消NSURLConnection

时间:2015-10-24 07:17:21

标签: ios nsmutableurlrequest

我在mapView drag / regionChange上调用webservice。我想在Web服务调用中保持一些延迟。所以我希望每当用户多次拖动地图时,应该取消之前的所有Web服务调用,并且只应触发最后一次拖动Web服务调用。

我该怎么做?

以下是我的代码:

{ .... NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
        [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
        [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];

        NSString *postLength = [NSString stringWithFormat:@"%lu",(unsigned long)[data length]];

        [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
        [request setHTTPBody:data];

        [request setHTTPMethod:@"POST"];
        NSMutableDictionary __block *dictResponse;
    [[NSOperationQueue mainQueue] cancelAllOperations];
        [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {

            if(connectionError == nil){

                dictResponse = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&connectionError];
                }

2 个答案:

答案 0 :(得分:2)

您无法取消sendAsynchronousRequest。如果您使用了基于委托的NSURLConnection请求,那么您可以取消它,但是(a)这比您可能想要打扰的编码更多; (b)NSURLConnection已被弃用,因此无论如何你都应该NSURLSession;和(c)NSURLSession允许您使用返回给您的NSURLSessionTask引用取消任务:

NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
[request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setHTTPBody:data];
[request setHTTPMethod:@"POST"];

NSURLSessionTask *task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
    if (error) {
        NSLog(@"connection error = %@", error);
        return;
    }
    NSError *parseError;
    NSDictionary *responseObject = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&parseError];
    if (!responseObject) {
        NSLog(@"parse error = %@", parseError);
    }
    dispatch_async(dispatch_get_main_queue(), ^{
        // use response here; e.g., updating UI or model objects
    });
}];
[task resume];

如果您需要取消此请求,请致电[task cancel]。因此,如果您想跟踪它并稍后取消它,请将此NSURLSessionTask保存在某个弱变量中。

答案 1 :(得分:1)

请勿使用sendAsynchronousRequest便捷API,请使用主委托API,以便您可以访问NSURLConnecyion的实例以致电cancel

另外,不要取消主要队列上的操作,你不知道那里有什么,并考虑使用NSURLSession