在ios中取消NSURLConnection

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

您无法取消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; eg, updating UI or model objects }); }]; [task resume]; 

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

不要使用sendAsynchronousRequest便捷API,使用主委托API,这样您就可以访问NSURLConnecyion实例来调用cancel

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