iOS开发中如遇到频繁的Http请求,如何取消之前已经发送的Http请求?
程序员文章站
2022-03-16 16:32:39
iOS开发中如遇到频繁的Http请求,如何取消之前已经发送的Http请求?
以上面的代码段为例,他是这么操作的
主要精髓在于
第一点:不要initialize a newAF...
iOS开发中如遇到频繁的Http请求,如何取消之前已经发送的Http请求?
以上面的代码段为例,他是这么操作的
主要精髓在于
第一点:不要initialize a newAFHTTPSessionManager object everytime 一定要把manager用成全局的
第二点:把请求返回的task对象丢进数组,下次触发的时候把遍历数组,把之前的所有任务[task cancel]
- //somewhereinyourclass,let'ssayinViewDidLoadyoushouldinittheAFHTTPSessionManagerobject
- -(void)viewDidLoad{
- [superviewDidLoad];
- ///createtheAFHTTPSessionManagerobject,we'regonnauseitineveryrequest
- self.manager=[[AFHTTPSessionManageralloc]init];
- self.manager.responseSerializer=[AFJSONResponseSerializerserializer];
- ///createanarraythatisgoingtoholdtherequeststaskwe'vesenttotheserver.sowecangetbacktothemlater
- self.arrayOfTasks=[NSMutableArraynew];
- ///discussion:
- ///anarrayholdsmultipleobjects.ifyoujustwanttoholdareftothelatesttaskobject
- ///thencreateapropertyofNSURLSessionDataTaskinsteadofNSMutableArray,andletitpointtothelatestNSURLSessionDataTaskobjectyoucreate
- }
- -(BOOL)textField:(UITextField*)textFieldshouldChangeCharactersInRange:(NSRange)rangereplacementString:(NSString*)string;{
- ///yourcodegoeshere
- ///.....
- ///.....
- ///.....
- ///.....
- ///tillwereach
- if(stringLength>=3){
- ///cancelallprevioustasks
- [self.arrayOfTasksenumerateObjectsUsingBlock:^(NSURLSessionDataTask*taskObj,NSUIntegeridx,BOOLBOOL*stop){
- [taskObjcancel];///whensendingcanceltothetaskfailure:blockisgoingtobecalled
- }];
- ///emptythearraOfTasks
- [self.arrayOfTasksremoveAllObjects];
- ///initnewtask
- NSURLSessionDataTask*task=[self.managerGET:urlStringparameters:nilsuccess:^(NSURLSessionDataTask*task,idresponseObject){
- ///yourcode
- }failure:^(NSURLSessionDataTask*task,NSError*error){
- ///yourcode
- }];
- ///addthetasktoourarrayOfTasks
- [self.arrayOfTasksaddObject:task];
- }
- returnYES;
- }