How to immediately force cancel an NSOperation with AFNetworking?

只谈情不闲聊 提交于 2019-11-29 05:15:38

After a full morning of digging through AFNetworking source code, it turns out that the reason my operations weren't canceling had nothing to do with the operations themselves, but rather because I've been starting the operations incorrectly all this time. I've been using

[NSOperation start];

when I should have been adding it to my HTTPRequestSingleton's operation queue:

[[[HTTPRequestSingleton sharedClient] operationQueue] addOperation:NSOperation];

Adding it to the queue allows it to be canceled properly without having to check the isCancelled property.

completionBlock

Returns the block to execute when the operation’s main task is complete.

  • (void (^)(void))completionBlock Return Value The block to execute after the operation’s main task is completed. This block takes no parameters and has no return value.

Discussion The completion block you provide is executed when the value returned by the isFinished method changes to YES. Thus, this block is executed by the operation object after the operation’s primary task is finished or cancelled.

Check the operation isCancelled property to understand why is the callback called.


Look into the initialization code:

+ (AFJSONRequestOperation *)JSONRequestOperationWithRequest:(NSURLRequest *)urlRequest
                                                    success:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, id JSON))success 
                                                    failure:(void (^)(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON))failure
{
    AFJSONRequestOperation *requestOperation = [[[self alloc] initWithRequest:urlRequest] autorelease];
    [requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        if (success) {
            success(operation.request, operation.response, responseObject);
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        if (failure) {
            failure(operation.request, operation.response, error, [(AFJSONRequestOperation *)operation responseJSON]);
        }
    }];

    return requestOperation;
}

What you'll want to do to get the operation var in the callback is to use setCompletionBlockWithSuccess after the JSONRequestOperationWithRequest:success:failure: initialization which is kind of overkill, the better way would be to copy the code and use

    AFJSONRequestOperation *requestOperation = [[[self alloc] initWithRequest:urlRequest] autorelease];
    [requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {

    // ... here you can check `isCancelled` flag
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!