gpt4 book ai didi

ios - 在 ios 中取消 NSURLConnection

转载 作者:行者123 更新时间:2023-12-01 18:48:09 26 4
gpt4 key购买 nike

我在 mapView 上调用网络服务拖动/区域更改。我想在 Web 服务调用中保持一些延迟。所以我希望每当用户多次拖动 map 时,应该取消所有以前的 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 .如果您使用基于委托(delegate)的 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如果您想跟踪它并稍后取消它,请在一些弱变量中。

关于ios - 在 ios 中取消 NSURLConnection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33315590/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com