AFNetworking 取消发布请求
Posted
技术标签:
【中文标题】AFNetworking 取消发布请求【英文标题】:AFNetworking cancel post request 【发布时间】:2016-01-22 14:45:10 【问题描述】:我知道,这个问题之前问过。但在这种情况下不适合我。我正在为传输层开发 AFNetworking。我的代码如下。
AFHTTPRequestOperation *post; AFHTTPRequestOperationManager *manager;
AFHTTPRequestOperationManager * manager = [AFHTTPRequestOperationManager manager];
NSMutableDictionary *paramDict = [[NSMutableDictionary alloc] init] ;
delegate = (id<ConnectionUtilDelegate>) delegateObject;
for (Parameter *param in parameterArray)
[paramDict setObject:param.value forKey:param.name];
NSDictionary *params = paramDict;
manager.responseSerializer = [AFJSONResponseSerializer serializer];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
[manager.operationQueue cancelAllOperations];
post = [manager POST:[NSString stringWithFormat:@"%@",url] parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject)
NSLog(@"JSON: %@", responseObject);
[delegate requestCompleted:responseObject];
failure:^(AFHTTPRequestOperation *operation, NSError *error)
[delegate requestFailed:error];
NSLog(@"Error: %@", error);
];
这是我的发帖请求。它的工作就像魅力。但有时某些请求可能会迟到。例如,我发送 2 个不同的帖子请求,名称为 P1(帖子 1)和 P2(帖子 2)。如果这些请求响应返回为 R1(响应 1)而不是 R2(响应 2)对我来说是可以的。但是,如果此请求响应返回为 R2(响应 2)而不是 R1(响应 1),则它是我的应用程序的原因。所以我想在发送新请求时取消旧请求。和
[帖子取消];
错误: [AFHTTPRequestOperation cancel]:消息发送到已释放实例 0x1723cbf0
不适合我。你有什么建议吗?
【问题讨论】:
【参考方案1】:正如我在您的代码中看到的,您为每个请求创建一个新的AFHTTPRequestOperationManager
instance,然后在新创建的AFHTTPRequestOperationManager
的 operationQueue 上执行cancelAllOperations
。我建议您创建一个 AFHTTPRequestOperationManager
类型的 sharedManager 并将这个单例对象用于您的所有请求:
+ (instancetype)sharedManager
static AFHTTPRequestOperationManager *instance;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^
instance = [AFHTTPRequestOperationManager manager];
);
return instance;
然后,您可以在执行新请求之前取消所有请求:
+ (void)cancelAllRequests
[[AFHTTPRequestOperationManager sharedManager].operationQueue cancelAllOperations];
当你调用上述方法时,所有请求都会失败,failure
block 会被调用。所以你需要检查操作是否在失败块中是cancelled
。这是最终的代码:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager sharedManager];
NSMutableDictionary *paramDict = [[NSMutableDictionary alloc] init] ;
delegate = (id<ConnectionUtilDelegate>) delegateObject;
for (Parameter *param in parameterArray)
[paramDict setObject:param.value forKey:param.name];
NSDictionary *params = paramDict;
manager.responseSerializer = [AFJSONResponseSerializer serializer];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
AFHTTPRequestOperation *post = [manager POST:[NSString stringWithFormat:@"%@",url] parameters:params
success:^(AFHTTPRequestOperation *operation, id responseObject)
[delegate requestCompleted:responseObject];
failure:^(AFHTTPRequestOperation *operation, NSError *error)
if (!operation.cancelled)
[delegate requestFailed:error];
];
[post start];
【讨论】:
以上是关于AFNetworking 取消发布请求的主要内容,如果未能解决你的问题,请参考以下文章