【发布时间】:2015-10-24 07:17:21
【问题描述】:
我正在mapViewdrag/regionChange 上调用 web 服务。我想在 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];
}
【问题讨论】:
-
在github.com/AFNetworking/AFNetworking/blob/master/AFNetworking/… 自己尝试AFNetworking。我认为这就是您所需要的
-
顺便说一句,你永远不想在主队列上调用
cancelAllOperations。它没有按照您在此处的意图进行,并且您无法保证某些其他任务向主队列添加了一些操作。此外,您无需指定请求的Content-Length,因为这是自动为您完成的。