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

该方法也是从stackOverFlow上找来的,真的是找死我了

以上面的代码段为例,他是这么操作的

主要精髓在于

第一点:不要initialize a new AFHTTPSessionManager object everytime 一定要把manager用成全局的

第二点:把请求返回的task对象丢进数组,下次触发的时候把遍历数组,把之前的所有任务[task cancel]

[objc]  view plain  copy
  1. // somewhere in your class, let's say in ViewDidLoad you should init the AFHTTPSessionManager object  
  2. - (void)viewDidLoad {  
  3.     [super viewDidLoad];  
  4.   
  5.     /// create the AFHTTPSessionManager object, we're gonna use it in every request  
  6.     self.manager = [[AFHTTPSessionManager alloc] init];  
  7.     self.manager.responseSerializer = [AFJSONResponseSerializer serializer];  
  8.   
  9.     /// 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  
  10.     self.arrayOfTasks = [NSMutableArray new];  
  11.     /// discussion:  
  12.     /// an array holds multiple objects. if you just want to hold a ref to the latest task object  
  13.     /// then create a property of NSURLSessionDataTask instead of NSMutableArray, and let it point to the latest NSURLSessionDataTask object you create  
  14.   
  15. }  
  16.   
  17.   
  18.   
  19. -(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string;{  
  20.     /// your code goes here  
  21.     /// .....  
  22.     /// .....  
  23.     /// .....  
  24.     /// .....  
  25.     /// till we reach  
  26.     if(stringLength>=3){  
  27.         /// cancel all previous tasks  
  28.         [self.arrayOfTasks enumerateObjectsUsingBlock:^(NSURLSessionDataTask *taskObj, NSUInteger idx, BOOLBOOL *stop) {  
  29.             [taskObj cancel]; /// when sending cancel to the task failure: block is going to be called  
  30.         }];  
  31.   
  32.         /// empty the arraOfTasks  
  33.         [self.arrayOfTasks removeAllObjects];  
  34.   
  35.         /// init new task  
  36.         NSURLSessionDataTask *task = [self.manager GET:urlString parameters:nil success:^(NSURLSessionDataTask *task, id responseObject){  
  37.            /// your code  
  38.         }failure:^(NSURLSessionDataTask *task, NSError *error){  
  39.            /// your code  
  40.         }];  
  41.   
  42.         /// add the task to our arrayOfTasks  
  43.         [self.arrayOfTasks addObject:task];  
  44.     }  
  45.     return YES;  
  46. }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值