AFNetworking 2.0 cancel specific task

前端 未结 3 628
伪装坚强ぢ
伪装坚强ぢ 2021-02-01 21:45

I am trying out afnetworking 2.0 and just trying to figure out how to cancel specific tasks. The old way would be to use something like

[self cancelAllHTTPOperat         


        
相关标签:
3条回答
  • 2021-02-01 21:48

    You can store the task in a variable so you can access it later:

    NSURLSessionDataTask* task = [self GET:path parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
                completionBlock(responseObject);
            } failure:^(NSURLSessionDataTask *task, NSError *error) {
                errorBlock(error);
            }];
    

    Then simply cancel it with [task cancel].

    Another way would be to save the task ID of the task and later ask the URL session for its tasks and identify the task you wish to cancel:

    // save task ID
    _savedTaskID = task.taskIdentifier;
    
    // cancel specific task
    for (NSURLSessionDataTask* task in [self dataTasks]) {
        if (task.taskIdentifier == _savedTaskID) {
            [task cancel];
        }
    }
    
    0 讨论(0)
  • 2021-02-01 21:54

    you can do the following

    NSArray *operations = [[[MyClient sharedClient] operationQueue] operations];
    if(operations && operations.count > 0){
        for (NSOperation *operation in operations) {
            if([operation isKindOfClass:[AFHTTPRequestOperation class]]){
                AFHTTPRequestOperation *httpOperation = (AFHTTPRequestOperation *)operation;
                NSLog(@"%@", [[httpOperation request] URL]);
                //--- if this is your request then cancel it --> [httpOperation cancel];
            }
        }
    }
    

    Where MyClient is a child of AFHTTPClient and the function sharedClient is a static function which returns a singleton instance of MyClient

    0 讨论(0)
  • 2021-02-01 22:08

    No need to save it, here is my implementation, use your subclass of AFURLSessionManager for cancelling specific request:

    - (void)cancelAllHTTPOperationsWithPath:(NSString *)path
    {
        AFURLSessionManager * yourSessionManager = [self getSessionManager];
    
        [[yourSessionManager session] getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
            [self cancelTasksInArray:dataTasks withPath:path];
            [self cancelTasksInArray:uploadTasks withPath:path];
            [self cancelTasksInArray:downloadTasks withPath:path];
        }];
    }
    
    - (void)cancelTasksInArray:(NSArray *)tasksArray withPath:(NSString *)path
    {
        for (NSURLSessionTask *task in tasksArray) {
            NSRange range = [[[[task currentRequest]URL] absoluteString] rangeOfString:path];
            if (range.location != NSNotFound) {
                [task cancel];
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题