iOS开发中如遇到频繁的Http请求,如何取消之前已经发送的Http请求?

主要精髓在于
第一点:不要initialize a new AFHTTPSessionManager object everytime 一定要把manager用成全局的
第二点:把请求返回的task对象丢进数组,下次触发的时候把遍历数组,把之前的所有任务[task cancel]

- (void)viewDidLoad {  
    [super viewDidLoad];  

    /// create the AFHTTPSessionManager object, we're gonna use it in every request  
    self.manager = [[AFHTTPSessionManager alloc] init];  
    self.manager.responseSerializer = [AFJSONResponseSerializer serializer];  

    /// create an array that is going to hold the requests task we've sent to the server. so we can get back to them later  
    self.arrayOfTasks = [NSMutableArray new];  
    /// discussion:  
    /// an array holds multiple objects. if you just want to hold a ref to the latest task object  
    /// then create a property of NSURLSessionDataTask instead of NSMutableArray, and let it point to the latest NSURLSessionDataTask object you create  

}  



-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string;{  
    /// your code goes here  
    /// .....  
    /// .....  
    /// .....  
    /// .....  
    /// till we reach  
    if(stringLength>=3){  
        /// cancel all previous tasks  
        [self.arrayOfTasks enumerateObjectsUsingBlock:^(NSURLSessionDataTask *taskObj, NSUInteger idx, BOOLBOOL *stop) {  
            [taskObj cancel]; /// when sending cancel to the task failure: block is going to be called  
        }];  

        /// empty the arraOfTasks  
        [self.arrayOfTasks removeAllObjects];  

        /// init new task  
        NSURLSessionDataTask *task = [self.manager GET:urlString parameters:nil success:^(NSURLSessionDataTask *task, id responseObject){  
           /// your code  
        }failure:^(NSURLSessionDataTask *task, NSError *error){  
           /// your code  
        }];  

        /// add the task to our arrayOfTasks  
        [self.arrayOfTasks addObject:task];  
    }  
    return YES;  
}  

注意:
这里的task cancel亲测确实能把网络请求cancel掉,可以看下面的log,记住一点,这里cancel之后不代表就不回调
了,只是会回调到error的那个block里面,各位需要信息的可以测试下,在error打个断点就能调试出来了

// 查看网络任务的状态  
[articleInterface.articleArrayTask enumerateObjectsUsingBlock:^(NSURLSessionDataTask *taskObj, NSUInteger idx, BOOLBOOL *stop) {  
    DDLogVerbose(@"当前的文章删除前网络任务状态是==================>>>>>%ld",taskObj.state);  
    [taskObj cancel]; /// when sending cancel to the task failure: block is going to be called  
    DDLogVerbose(@"当前的文章删除后网络任务状态是==================>>>>>%ld",taskObj.state);  
}];  
typedef NS_ENUM(NSInteger, NSURLSessionTaskState) {  
    NSURLSessionTaskStateRunning = 0,                     /* The task is currently being serviced by the session */  
    NSURLSessionTaskStateSuspended = 1,  
    NSURLSessionTaskStateCanceling = 2,                   /* The task has been told to cancel.  The session will receive a URLSession:task:didCompleteWithError: message. */  
    NSURLSessionTaskStateCompleted = 3,                   /* The task has completed and the session will receive no more delegate notifications */  
} NS_ENUM_AVAILABLE(NSURLSESSION_AVAILABLE, 7_0);  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值