ASIHTTPRequest Request Cancel - iphone

I have been using ASIHTTPRequest to fetch the data and i want to cancel the request how i do it??
i do the code just like this..
-(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");
}
//if i press cancel button(when requestFinished /requestFailed method in process ) then the ASIHTTPRequest fail and finish method Stop /abort! how i do this??
-(IBAction)CancleREquest:(id)sender{
NSLog(#"CancleREquest");
}

Your cancel specific ASIHTTPRequest then :
if(![yourASIHTTPRequest isCancelled])
{
// Cancels an asynchronous request
[yourASIHTTPRequest cancel];
// Cancels an asynchronous request, clearing all delegates and blocks first
[yourASIHTTPRequest clearDelegatesAndCancel];
}
Note : To cancel all ASIHTTPRequest then :
for (ASIHTTPRequest *request in ASIHTTPRequest.sharedQueue.operations)
{
if(![request isCancelled])
{
[request cancel];
[request setDelegate:nil];
}
}
EDIT : Use AFNetworking as ASIHTTPRequest is deprecated as its has not been update since march 2011.

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

I suggest you to keep a reference to the pending request in an ivar/property of your controller, then send the cancel message to it from your button handler.
//-- 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");
}
You have several options when canceling, though; from ASIHTTPRequest 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];

Related

ASIHTTPRequest multiple downloads control like pause, resume

I am using ASIHTTPRequest to download video file from URL in background.
I am displaying the downloads with progress-bar & percentage and I want user can control the downloads like pause & resume.
Below is the code:
-(void)Initiate_Download:(NSString*)urlStr contentID:(NSString*)cid progressBar:(UIProgressView*)progressBar
{
NSLog(#"Initiate_Download for cid:%#",cid);
urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:urlStr]];
NSString *fileName = [NSString stringWithFormat:#"%#.mp4",cid];
NSString *destinationPath = [[self VideoDownloadFolderPath]stringByAppendingPathComponent:fileName];
[request setDownloadDestinationPath:destinationPath];
[request setTemporaryFileDownloadPath:[NSString stringWithFormat:#"%#-part",destinationPath]];
[request setDelegate:self];
NSDictionary *rqstDict = [NSDictionary dictionaryWithObjectsAndKeys:cid,#"cid",urlStr,#"url", nil];
[request setUserInfo:rqstDict];
[request setAllowResumeForFileDownloads:YES];
[request startAsynchronous];
}
//Delegate
- (void)requestStarted:(ASIHTTPRequest *)request1
{
//some code
}
- (void)request:(ASIHTTPRequest *)request1 didReceiveResponseHeaders:(NSDictionary *)responseHeaders
{
//some code
}
- (void)requestFinished:(ASIHTTPRequest *)request1
{
//some code
}
- (void)requestFailed:(ASIHTTPRequest *)request1
{
//some code
}
You need to save the URL and destination path of the request for each request and to pause the request use code :-
[request Cancel];
and to resume the request you need to create another request with same URL and destination path. For example :-
ASIHTTPRequest *requestToResume = [ASIHTTPRequest requestWithURL:url];
[requestToResume setTemporaryFileDownloadPath:tempfilePath];
[requestToResume setDownloadDestinationPath:filePath];
[requestToResume setDelegate:self];
[requestToResume setDownloadProgressDelegate:self];
[requestToResume setUserInfo:dictInfo];
// This file has part of the download in it already
[requestToResume setAllowResumeForFileDownloads:YES];
[requestToResume setDidFinishSelector:#selector(requestDone:)];
[requestToResume setDidFailSelector:#selector(requestWentWrong:)];
[requestToResume startAsynchronous];
In the above code we get the url of the song from the dictionary which was set as userInfo of the request and now we get these details for resuming the request. When we resume the request the file will be downloaded from the point it was paused, hence it will solve the purpose of resuming the file download.

UIActivityIndicator

When I start UIActivityIndicatorView using StartAnimating method:
[ActivityIcon startAnimating];
it disable all user interactions so when the user Tap on Cancel button which should abort the download process and hide the UIActivityIndicator it does not work!!!
any suggestions would be appreciated.
Edit:
I am using separate thread to download the files in the background. All progress reporting and UI interaction I made it through:
[self performSelectorOnMainThread:#selector(RefreshScreen:) withObject:nil waitUntilDone:YES];
and RefreshScreen method is the one who interact with the UI elements.
try change this line: [request startSynchronous]; to: [request startAsynchronous];
EDIT
- (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];
}

cancel ASIHTTP request

I used ASIHTTP request to access web html page.
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:requestURL]];
[request setTag:selectTag];
[request setDownloadCache:[ASIDownloadCache sharedCache]];
[request setCachePolicy:ASIAskServerIfModifiedCachePolicy | ASIFallbackToCacheIfLoadFailsCachePolicy];
[request setCachePolicy:ASIOnlyLoadIfNotCachedCachePolicy];
[request setDelegate:self];
[request startAsynchronous];
If I navigate from an ViewController to another.
Is it possible to cancel this async http request if it has not yet triggered 'requestFinished'?
Welcome any comment
Following method is present with ASIHttpRequest, you can use it to cancel the request -
- (void)cancel {
[self performSelector:#selector(cancelOnRequestThread) onThread:[[self class] threadForRequest:self] withObject:nil waitUntilDone:NO];
}
You can call this method-
[request cancel];

Canceling a ASIHTTPRequest - Beginner

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];
}
for (ASIHTTPRequest *req in ASIHTTPRequest.sharedQueue.operations)
{
[req cancel];
[req setDelegate:nil];
}
this should cancel it..
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.
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];

Problem with hiding modalviewcontroller using ASIHTTPRequest

I have a problem with hiding modalviewcontroller when I connect to server with ASIHttpRequest.
I connect in background thread and show modalview in main thread.
This is my code:
[self performSelectorInBackground:#selector(loginServerRequest) withObject:nil];
- (void)loginServerRequest {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSURL *url = [NSURL URLWithString:#"https://11.111.111.11/api/login"];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setPostValue:[AccountSettings getCompany] forKey:#"companyName"];
[request setPostValue:[AccountSettings getEmail] forKey:#"email"];
[request setPostValue:[AccountSettings getPassword] forKey:#"password"];
[request setRequestMethod:#"POST"];
[request setTimeOutSeconds:10];
[request setValidatesSecureCertificate:NO];
[request setDelegate:self];
[request startSynchronous];
[pool drain];
}
- (void)requestFinished:(ASIHTTPRequest *)request
{
[self performSelector:#selector(hideServerConnectView) withObject:nil afterDelay:0.0];
int status = [request responseStatusCode];
NSLog(#"%i", status);
if ([self.nibName isEqualToString:#"RootViewController"]) {
if (status == 200) {
//some code
}
}
}
- (void)hideServerConnectView {
[self.parentViewController dismissModalViewControllerAnimated:NO];
}
If server responses immediately modalviewcontroller doesn't hide!
If pass some seconds then everything is okay.
What's the problem??
I changed my code like this:
[self loginServerRequest];
ServerConnectView *viewC = [[ServerConnectView alloc] init];
[self.view addSubview:viewC.view];
[self presentModalViewController:viewC animated:YES];
[viewC release];
- (void)loginServerRequest {
NSURL *url = [NSURL URLWithString:#"https://11.111.111.11/api/login"];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setPostValue:[AccountSettings getCompany] forKey:#"companyName"];
[request setPostValue:[AccountSettings getEmail] forKey:#"email"];
[request setPostValue:[AccountSettings getPassword] forKey:#"password"];
[request setRequestMethod:#"POST"];
[request setTimeOutSeconds:10];
[request setValidatesSecureCertificate:NO];
[request setDelegate:self];
[request startAsynchronous];
}
- (void)requestFinished:(ASIHTTPRequest *)request{
[self hideServerConnectView];
int status = [request responseStatusCode];
NSLog(#"%i", status);
if ([self.nibName isEqualToString:#"RootViewController"]) {
if (status == 200) {
//some code
}
}
}
- (void)hideServerConnectView {
[self.parentViewController dismissModalViewControllerAnimated:NO];
}
And it didn't solve my problem.
Any ideas? Or something wrong?
You're mixing async and sync methods.
You set up the request as though it's an async request, but then call [request startSynchronous];.
Because of this, the delegate methods will not be called and your modal will not be dismissed.
The fix is to fire off the request async, using [request startAsynchronous];
This also means that you don't need to call performSelectorInBackground (or setup the autorelease pool in the loginServerRequest method).
In your asynchronous version, move [self hideServerConnectView]; just after [self loginServerRequest];
OR use - (void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait to invoke - (void)hideServerConnectView since UI update must occur on the Main Thread.