4

我一直在使用 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 失败并完成方法停止 /abort!我该怎么做??

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

3 回答 3

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 月以来没有更新。

于 2012-05-28T07:18:53.310 回答
6

不错的简单版本:

for (ASIHTTPRequest *request in ASIHTTPRequest.sharedQueue.operations){
    [request cancel];
    [request setDelegate:nil];
}
于 2012-11-20T10:31:49.687 回答
1

我建议您在控制器的 ivar/属性中保留对挂起请求的引用,然后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 文档

取消异步请求

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

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

            // Cancels an asynchronous request
            [request cancel]

            // Cancels an asynchronous request, clearing all delegates and blocks first
            [request clearDelegatesAndCancel];
于 2012-05-28T07:14:10.197 回答