ASIHTTPRequest请求取消

时间:2012-05-28 07:11:14

标签: iphone objective-c xcode asihttprequest

我一直在使用ASIHTTPRequest来获取数据,我想取消请求我是怎么做到的? 我就像这样做代码..

-(void) serachData{
   NSURL *url= [NSURL URLWithString:self.safestring];
    ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
    [request setTimeOutSeconds:7200];
    [request setDelegate:self];
    [request startAsynchronous];
}

 - (NSMutableDictionary *)requestFinished:(ASIHTTPRequest *)request
 {
   NSLog(@"requestFinished");
    NSString *responseString = [request responseString];
    SBJsonParser *json = [[SBJsonParser alloc] init];
    NSMutableArray *array = [[NSMutableArray alloc] initWithObjects[jsonobjectWithString:responseString], nil];
     NSLog(@"array %@",array);
  }

  - (void)requestFailed:(ASIHTTPRequest *)request{
 NSLog(@"requestFailed");
 }

//如果我按下取消按钮(当处理requestFinished / requestFailed方法时),则ASIHTTPRequest失败并完成方法停止/中止!我是怎么做到的?

 -(IBAction)CancleREquest:(id)sender{
NSLog(@"CancleREquest");
   }

3 个答案:

答案 0 :(得分:9)

取消特定的ASIHTTPRequest 然后:

if(![yourASIHTTPRequest isCancelled]) 
{
    // Cancels an asynchronous request
    [yourASIHTTPRequest cancel];
    // Cancels an asynchronous request, clearing all delegates and blocks first
    [yourASIHTTPRequest clearDelegatesAndCancel];
}

注意:要取消所有 ASIHTTPRequest ,请:

for (ASIHTTPRequest *request in ASIHTTPRequest.sharedQueue.operations)
{
  if(![request isCancelled]) 
  {
     [request cancel];
     [request setDelegate:nil];
  }
}

编辑:使用AFNetworking因为ASIHTTPRequest已弃用,因为自2011年3月以来尚未更新。

答案 1 :(得分:6)

简单易懂的版本:

for (ASIHTTPRequest *request in ASIHTTPRequest.sharedQueue.operations){
    [request cancel];
    [request setDelegate:nil];
}

答案 2 :(得分:1)

我建议您在控制器的ivar / property中保留对待处理请求的引用,然后从按钮处理程序向其发送cancel消息。

//-- in your  class interface:
@property (nonatomic, assign) ASIFormDataRequest *request;

....

//-- in your  class implementation:
@synthesize request;

.....

-(void) serachData{
   NSURL *url= [NSURL URLWithString:self.safestring];
   self.request = [ASIFormDataRequest requestWithURL:url];
   [self.request setTimeOutSeconds:7200];
   [self.request setDelegate:self];
   [self.request startAsynchronous];
}

-(IBAction)CancleREquest:(id)sender{
   [self.request cancel];
   NSLog(@"request Canceled");
}

但取消时你有几个选择;来自ASIHTTPRequest docs

  

取消异步请求

     

要取消异步请求(使用[request startAsynchronous]启动的请求或在您创建的队列中运行的请求),请调用[request cancel]。请注意,您无法取消同步请求。

     

请注意,当您取消请求时,请求会将其视为错误,并将调用您的委托和/或队列的失败委托方法。如果您不想要这种行为,请在调用cancel之前将委托设置为nil,或者使用clearDelegatesAndCancel方法。

            // Cancels an asynchronous request
            [request cancel]

            // Cancels an asynchronous request, clearing all delegates and blocks first
            [request clearDelegatesAndCancel];