2012-05-28 176 views
4

我一直在使用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"); 
    } 

回答

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]; 
    } 
} 

编辑:使用AFNetworkingASIHTTPRequest被弃用其并没有因为被更新2011年3月

+0

加上'为(ASIHTTPRequest *在ASIHTTPRequest.sharedQueue.operations要求)'来获取'request'变量。 – dvdfrddsgn

1

我建议你保持到挂起请求引用您的控制器的伊娃/属性,然后从你的按钮处理程序发送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

取消异步请求

要取消的异步请求(这是开始使用[请求startAsynchronous]请求或在创建一个队列运行的请求),调用[请求取消] 。请注意,您无法取消同步请求。

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

  // Cancels an asynchronous request 
      [request cancel] 

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

尼斯简单的版本:

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