1
votes

I am using ASIHTTPRequest to send request to web server. It all works fine. But now, when i call the grabURLInBackground method, a request is sent to the given URL.

But now, i need to cancel the request (as in stop sending, and stop downloading the content from the URL), in the viewWillDissapear method. How can i do this ? Help

- (IBAction)grabURLInBackground:(id)sender
{
   NSURL *url = [NSURL URLWithString:@"http://allseeing-i.com"];
   ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
   [request setDelegate:self];
   [request startAsynchronous];
}

- (void)requestFinished:(ASIHTTPRequest *)request
{
   // Use when fetching text data
   NSString *responseString = [request responseString];

   // Use when fetching binary data
   NSData *responseData = [request responseData];
}

- (void)requestFailed:(ASIHTTPRequest *)request
{
   NSError *error = [request error];
}
3

3 Answers

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

this should cancel it..

2
votes

You can do:

[request cancel]

Or:

[request clearDelegatesAndCancel];

As can be seen in the documentation here.

I'd suggest storing a reference to that request so you can cancel it when leaving the view.

2
votes

GOt thsi from ASIHttp docs:

Cancelling an asynchronous request

To cancel an asynchronous request (either a request that was started with [request startAsynchronous] or a request running in a queue you created), call [request cancel]. Note that you cannot cancel a synchronous request.

Note that when you cancel a request, the request will treat that as an error, and will call your delegate and/or queue’s failure delegate method. If you do not want this behaviour, set your delegate to nil before calling cancel, or use the clearDelegatesAndCancel method instead.

// Cancels an asynchronous request

[request cancel]

// Cancels an asynchronous request,

clearing all delegates and blocks first [request clearDelegatesAndCancel];When using an ASINetworkQueue, all other requests will be cancelled when you cancel an individual request unless the queue’s shouldCancelAllRequestsOnFailure is NO (YES is the default).

// When a request in this queue fails or is cancelled, other requests will continue to run

[queue setShouldCancelAllRequestsOnFailure:NO];

// Cancel all requests in a queue

[queue cancelAllOperations];