cancel ASIHTTP request - iphone

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

Related

What are the working of ASIFormDataRequest and ASINetworkQueue in Iphone

ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:#"http://trade2rise.com/project/dry/windex.php?itfpage=register"]];
ASINetworkQueue *networkQueue = [[ASINetworkQueue alloc] init];
[request setPostValue:txt_name.text forKey:#"name"];
[request setPostValue:txt_con_number.text forKey:#"phone"];
[request setPostValue:txt_email.text forKey:#"email"];
[request setPostValue:txt_pwd.text forKey:#"password"];
[request setPostValue:txt_con_pwd.text forKey:#"password2"];
[request setDelegate:self];
[request setDidFinishSelector:#selector(requestFinished:)];
[request setDidFailSelector:#selector(requestFailed:)];
[networkQueue addOperation:request];
[networkQueue go];
I am new for the Iphone Please explain about abodve term?
If you known the http post method , you will known the key and value pair at the post form. so the code above just like add relative key and value to the form, the add the queue to post request.
ASIFormDataRequest *request // the url bind request,just form post form
ASINetworkQueue *networkQueue // the work queue to maintain the request in a queue (FIFO)

not saving when using setDidReceiveDataSelector

i want to download a file and show the progress bar
i was able to do this.
now , i want to show the progress value in a label and use this code to progress init and update label :
[queue setDelegate:self];
[queue setRequestDidFinishSelector:#selector(updateLabel)];
[queue setDownloadProgressDelegate:progress];
[queue setShowAccurateProgress:YES];
ASIHTTPRequest *request;
request = [ASIHTTPRequest requestWithURL:url];
[request setDelegate:self];
[request setTemporaryFileDownloadPath:[filePath stringByAppendingString:#".download"]];
[request setAllowResumeForFileDownloads:YES];
[request setDidFinishSelector:#selector(updateLabel)];
[request setDidReceiveDataSelector:#selector(updateLabel)];
[request setShouldContinueWhenAppEntersBackground:YES];
[request setShouldAttemptPersistentConnection:NO];
[request setDownloadDestinationPath:filePath];
[queue addOperation:request];
[queue go];
but not save in the destination path !
and when i clear this code : 
[request setDidReceiveDataSelector:#selector(updateLabel)];
saving done !
what is problem ?
i want to update label text when progress value changed
This is what something you need to do with the Main Thread. Updating the UI of the application is performed by the main thread rather than any of the background thread.
Or
alternatively you can use the below code snippet which works for me :
- (void)fetchThisURLFiveTimes:(NSURL *)url
{
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request addOperation:request];
[request cancelAllOperations];
[request setDownloadProgressDelegate:myProgressIndicator];
[request setDelegate:self];
[request setRequestDidFinishSelector:#selector(queueComplete:)];
[request go];
}
- (void)queueComplete:(ASINetworkQueue *)queue
{
NSLog(#"Value: %f", [myProgressIndicator progress]);
[self performSelectorOnMainThread:#selector(updateLabel) withObject:nil waitUntilDone:NO];
}

ASIHTTPRequest Request Cancel

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

Sending POST request in iPhone using ASIHTTPRequest 1.6.2

I am using ASIHTTPRequest 1.6.2 lib for all http transactions in IPhone. But i dont know, how can i post the data with ASIHTTPRequest in iPhone?
Can you please give me the code snippet which will work in in iphone?
I am using the following code for this. But i am getting response code as 0. Please help me to understand where i am going wrong.
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setPostValue:inputXml forKey:#"inputXml"];
[request setPostValue:#"qftS6TJN343343V84hw=" forKey:#"key"];
[request setPostValue:#"1.2" forKey:#"version"];
[request setRequestMethod:#"POST"];
[request startAsynchronous];
You should use ASIFormDataRequest:
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setPostValue:#"Ben" forKey:#"first_name"];
[request setPostValue:#"Copsey" forKey:#"last_name"];
[request setFile:#"/Users/ben/Desktop/ben.jpg" forKey:#"photo"];
Here's the how to page. It covers all types of requests such as get, form post, custom post, put, etc...
http://allseeing-i.com/ASIHTTPRequest/How-to-use
Here's how to set it up in your XCode project:
http://allseeing-i.com/ASIHTTPRequest/Setup-instructions
Those instructions and snippets should work in iOS.
Following is the sample code...
ASIHTTPRequest *request = [[ASIHTTPRequest alloc] initWithURL:url];
[request appendPostData:[reqString dataUsingEncoding:NSUTF8StringEncoding]];
[request setRequestMethod:#"POST"];
[request setDelegate:self];
[request setTimeOutSeconds:60];
[request startAsynchronous];
You will get detail guidance from here.
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:]];
NSMutableDictionary *dicData = [[NSMutableDictionary alloc] initWithCapacity:1];
[dicData setObject:txtPassword.text forKey:#"Password"];
[dicData setObject:txtEmailID.text forKey:#"Email"];
[request setPostBody:[[[self parseJsonFromObject:dicData] dataUsingEncoding:NSUTF8StringEncoding] mutableCopy]];
[request setRequestHeaders:[NSMutableDictionary dictionaryWithObjectsAndKeys:#"application/json", #"Content-Type", nil]];
[request setDelegate:self];
[request setDidFinishSelector:#selector(signUpWithEmailFinish:)];
[request setDidFailSelector:#selector(signUpWithEmailFail:)];
[request startAsynchronous];
(void)signUpWithEmailFinish:(ASIHTTPRequest *)request
{
if (request.responseStatusCode == 200)
{
NSDictionary *responseMessage = [self objectFromJson:request.responseString];
NSLog(#"ResponseMEssage=%#",responseMessage);
if (responseMessage)
{
if ([responseMessage objectForKey:#"user"] == nil)
{
NSLog(#"duplication not allowed");
[self animation:0];
return;
}
[[NSNotificationCenter defaultCenter] postNotificationName:NOTIFICATION_LOGIN_SUCCESS object:nil];
NSLog(#"Registration Complete");
UserLoginPage *userLogin=[[UserLoginPage alloc]init];
[self.navigationController pushViewController:userLogin animated:YES];
return;
}
}
}

How do I use ASI Http in iOS to POST data to a web service?

I am using the instructions provided in the ASI page here. I am trying to send some data to a web service and not seeing any results.
This is my sendRequest method which gets called in viewDidLoad
-(void)sendRequest {
NSURL *url = [NSURL URLWithString:#"http://153.60.6.75:8080/BarcodePayment/transactions"];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request addRequestHeader:#"Accept" value:#"application/json"];
[request addRequestHeader:#"Content-Type" value:#"application/json"];
NSString *dataContent = #"{\"id\":7,\"amount\":7.0,\"paid\":true}";
NSLog(#"dataContent: %#", dataContent);
[request appendPostData:[dataContent dataUsingEncoding:NSUTF8StringEncoding]];
[request setRequestMethod:#"POST"];
}
I check the dataContent string and the output is
{"id":7,"amount":7.0,"paid":true}
If I use curl from Terminal, I checked and this command works.
curl -X POST -H 'Accept:application/json' -H 'Content-Type: application/json' http://153.60.6.75:8080/BarcodePayment/transactions/ --data '{"id":7,"amount":7.0,"paid":true}'
My understanding is that in using curl, I set it to json, specify the address, specify the data which is equivalent to dataContent in my code. Nothing happens. What's wrong?
Thanks for the help!
You have pretty much everything except the most crucial component which is to start the request
You need to add [request startSynchronous]; for a Synchronous Request or [requester startAsynchronous]; for a Asynchronous request (and you possibly need the Delegate Methods to handle any response you have back)
This is all covered pretty nicely in the ASIHTTPRequest How to Use Guide. The Sections most relevant to this would be 'Creating a synchronous request' and 'Creating an asynchronous request'. Also something to think about taken from that page:
In general, you should use asynchronous requests in preference to synchronous requests. When you use ASIHTTPRequest synchronously from the main thread, your application’s user interface will lock up and become unusable for the duration of the request.
You forgot to call:
[request setDelegate: self];
[request startAsynchronous];
Or:
[request startSynchronous];
If you don't call any of these, the request will never be made :)
I don't see a call to [request startSynchronous] (or [request startAsynchronous]) in your code... Are you even initiating the request anywhere?
It looks like you didn't call [request startAsynchronous];
Check ASIHTTPRequest documentation for more details on how to use
You're not actually sending the request.
1) You'll need to call [request startSynchronous] or [request startAsynchronous]
2) If you use asynchronous (which you should probably do) you'll need to set the delegate and implement a - (void)requestFinished:(ASIHTTPRequest *)request method.
- (void)postThresholdDetails:(NSDictionary *)info
{
NSString *urlString = [NSString stringWithFormat:#"%#%#/",BaseUrl,PostThresholdDetails];
NSURL *url = [NSURL URLWithString:urlString];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setRequestMethod:#"POST"];
[request setDelegate:self];
[request setTimeOutSeconds:120];
[request addRequestHeader:#"Accept" value:#"application/json"];
[request addRequestHeader:#"content-type" value:#"application/x-www-form-urlencoded"];
request.allowCompressedResponse = NO;
request.useCookiePersistence = NO;
request.shouldCompressRequestBody = NO;
[request setPostBody:[NSMutableData dataWithData: [info objectForKey:#"jsondata"] ]];
[request startAsynchronous];
}