ASIHTTPRequest in iOS - iphone

I have been using ASIHTTPRequest for an application but it gives me error in topSecretFetchFailed method 5 out of 10 request, Not sure how to deal with it, Isn't ASIHTTPRequest stable enough?
[request setDidFailSelector:#selector(topSecretFetchFailed:)];
EDIT:
This is my code or method which get called in each request. MARKET_INDEXES_URL its static string which has "someurl.com";
- (void)requestData {
ASIHTTPRequest *req = [ASIHTTPRequest requestWithURL:[NSURLURLWithString:MARKET_INDEXES_URL]];
[req setDelegate:self];
[req setDidFailSelector:#selector(topSecretFetchFailed:)];
[req setDidFinishSelector:#selector(topSecretFetchComplete:)];
[self setRequest:req];
[self.request startAsynchronous];
}
and this is the fail handler
- (void)topSecretFetchFailed:(ASIHTTPRequest *)theRequest {
[[NSNotificationCenter defaultCenter] postNotificationName:#"MarketIndexesError" object:nil];
UIAlertView *view = [[UIAlertView alloc] initWithTitle:#"Warning !" message:#"Connection error, Please try again" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[view show];
[view release];
NSLog(#"MarketIndex service Fail: %d %#", [theRequest responseStatusCode], [theRequest responseStatusMessage]);
}

What you need is some reporting of the response details. Without that, you're diagnosing in the dark. Put this in your failure handler:
NSLog(#"Fail: %d %#", [request responseStatusCode], [request responseStatusMessage]);

ASIHTTPRequest is stable. You are probably getting error because either your network is down or your server is taking too long to respond.
You should try changing the ASIHTTPRequest property numberOfTimesToRetryOnTimeout to something that suits you.
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:....
request.numberOfTimesToRetryOnTimeout=10;

Related

NSURLConnection error not working

I am trying to detect if there is an error in my request using the if statement on theConnection. It enters the first part if successful fine but does not enter the else if there is an error. I am not sure why.
- (void)vehicleSearchRequest:(NSData *)postBodyData
{
NSString *address = [NSString stringWithFormat:#"http://%#", serverAddress];
//Set database address
NSMutableString *databaseURL = [[NSMutableString alloc] initWithFormat:#"%#", address];
NSURL *url = [NSURL URLWithString:databaseURL];
NSString *postLength = [NSString stringWithFormat:#"%d", [postBodyData length]];
//SynchronousRequest to grab the data, also setting up the cachePolicy
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; //if request dose not finish happen within 60 second timeout.
// Set up request
[request setHTTPMethod: #"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/octet-stream" forHTTPHeaderField:#"content-type"];
[request setHTTPBody:postBodyData];
[request setTimeoutInterval:180];
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:request delegate:self];
if (theConnection) {
// do animation thankyou here
NSLog(#"Sucsess!");
[self submitSuccessful];
} else {
// Inform the user that the connection failed from the connection:didFailWithError method
NSLog(#"Connectin ERROR!!!");
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Connection error, Please try again" message:nil delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
}
Your code checks to see whether it was able to instantiate an NSURLConnection or not. This is a useful safety check, but will only fail in practice if you pass it a URL that the system does not support.
The connection itself is asynchronous, and so will take a little while to tell you if there was a problem or not. Implement its delegate methods to hear back from the server.

Login to system in iphone.

I am new in iphone internet programming. I am writing an app which has login screen.
I am using ASIHTTPREQUEST, this is the link myurl.com/index.php what I want to login. In chrome, I looked at from the developer console this url posts to myurl.com/ajax/login.php when I login the system with username and password.
Anyway, when I click the login button after entering username and password in app, it doesn't login the system.It prints the FAIL:1 ( when I write myurl.com/ajax/login.php, FAIL:1 seen in the browser.)
Detailed description of my problem:
"There is an login screen in myurl.com/index.php. And in web browser, if I write my username and passw, It posts to myurl.com/ajax/login.php ( from the developer console). Anyway, in app I have written myurl.com/index.php as a url but when I request it prints the html elements of that page in console. If I write myurl.com/ajax/login.php as a url, it prints FAIL:1 in console. ( normally in web browser I have written myurl.com/ajax/login.php, it gives an FAIL:1)"
Edit: I have solved problem, "forKey: #"username" need to be equal "forKey: #"ID" and "forKey: #"password" need to be equal "forKey: #"PWD". Because in developer console username and password returned as a ID and PWD. Thanks for comment and answer.
This is the code:
-(IBAction)login:(id)sender
{
NSURL *url = [[NSURL alloc] initWithString:#"https://myurl.com/index.php"];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setTimeOutSeconds:120];
[request setPostValue:studentid.text forKey:#"username"];
[request setPostValue:starspassword.text forKey:#"password"];
[request setDelegate:self];
[request startAsynchronous];
[url release];
}
-(void) requestFinished:(ASIHTTPRequest *)request
{
NSString *responseString = [request responseString];
UIAlertView *alert= [[[UIAlertView alloc] initWithTitle:#"Success" message:#"http works"
delegate:self cancelButtonTitle:#"okay" otherButtonTitles:nil] autorelease];
[alert show];
NSLog(#"SUCCESS: %#", responseString);
//Request succeeded
}
-(void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
{
}
-(void) requestFailed:(ASIHTTPRequest *)request
{
NSError *error = [request error];
NSLog(#"ERROR: %#", [error localizedDescription]);
UIAlertView *alert= [[[UIAlertView alloc] initWithTitle:#"fail" message:#"http fails" delegate:self cancelButtonTitle:#"okay" otherButtonTitles:nil]autorelease];
[alert show];
//Request failed
}
Sorry for my english, there are some examples about this topic but I didn't solve this problem. Thanks for your advice.
Have you tried this instead? ASI includes a way to do basic authentication
[request setUsername:studentid.text];
[request setPassword:starspassword.text];
Scroll down to Handling HTTP Authentication
http://allseeing-i.com/ASIHTTPRequest/How-to-use

ASIHTTPRequest login page

I try to make an iphone application that can login to the web application that use the https securing the user information.Now i am stuck in the login page. I don't know how to check the real account in the website of user when logging in by my application. I got the response only 200 even if i put the wrong account.
here is my code:
- (IBAction)clickOK:(id)sender {
NSURL *url = [NSURL URLWithString:#"https://www.freelancer.com/users/login.php"];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setUseKeychainPersistence:YES];
[request setDelegate:self];
request.shouldPresentCredentialsBeforeChallenge = YES;
[request setRequestMethod:#"POST"];
[request setPostValue:usernameField.text forKey:#"username"];
[request setPostValue:passwordField.text forKey:#"passwd"];
request.timeOutSeconds = 30;
[request setDidFailSelector:#selector(requestLoginFailed:)];
[request setDidFinishSelector:#selector(requestLoginFinished:)];
[request startAsynchronous];
}
- (void)requestLoginFailed:(ASIHTTPRequest *)request
{
//notify user
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Error sending request to the server" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
- (void)requestLoginFinished:(ASIHTTPRequest *)request
{
int statusCode = [request responseStatusCode];
NSString *statusMessage = [request responseStatusMessage];
NSLog(#"StatusCode: %d", statusCode);
NSLog(#"StatusMessage: %#", statusMessage);
}
Can anyone suggest me how to check the real account of this website and keep user login?
Thanks for any help
You've started something Asynchronously
[request startAsynchronous];
And then just expected it to return something straight away:
NSLog(#"%#",[request responseString]);
NSLog(#"%d",[request responseStatusCode]);
You need to put something like this:
[request setDidFinishSelector:#selector(didFinishRequest:)];
And then move your NSLogs and any other stuff that leeches off of the response into that method.

How to periodically poll data from server on a background thread?

I have a chat like app, and to receive periodic chats, I want to poll server at regular intervals , say 5 mins..and check if there are any new messages.
As a beginner, I have tried simple NSURLConnection and send and receive data, but stuck while polling.
What is a correct way of polling? Should I use NSTimer to poll regularly?
Is there any sample code that can help me?
I have a timer running on main thread which invokes a background thread every 5 seconds and sends request to server. Now what happening is, the delegates for NSURLConnection are not getting called. What can be done?
Please help.
Thanks
You can launch an NSTimer on a background thread and make calls to the main thread periodically, this is how I do it:
[self performSelectorOnMainThread:#selector(LaunchTimer) withObject:nil waitUntilDone:NO];
Just make a "LaunchTimer" function that calls an update function at a certain interval, which makes a call to NSURLConnection, and when you receive the new messages, update the chat window by making a call to the main thread like so:
[self performSelectorOnMainThread:#selector(update:) withObject:newMessages waitUntilDone:NO];
Continuing from answer of Patrick :- If you can try NSURLConnection without delegate,
-(void)update:(id)objmessage
{
NSString *post =[NSString stringWithFormat:#"timestamp=%#&user_id=%#",DatetimeString,UID];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:#"Your server URL"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSError *error;
NSURLResponse *response;
NSData *returnData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
returnString=[[NSString alloc]initWithData:returnData encoding:NSUTF8StringEncoding];
if(!returnString)
{
UIAlertView *erroralert = [[UIAlertView alloc] initWithTitle:#"Error" message:#"There is an error getting response" delegate:self cancelButtonTitle:nil otherButtonTitles:#"OK", nil];
[erroralert show];
[erroralert release];
}
else
{
NSLog(#"%#",returnString);
}
SBJSON *json = [[SBJSON new] autorelease];
NSMutableDictionary *dic = [[NSMutableDictionary alloc] initWithDictionary:[json objectWithString:returnString error:nil]];
//NSLog(#"%#",dic);
}
Solved this with following method:
[self performSelectorOnMainThread:#selector(performPollinginBackground) withObject:nil waitUntilDone:NO];
-(void)performPollinginBackground{
//call server task here
}

ASI HTTP Request for posting a review

In my app I am sending a ASI HTTP post request so I user can post a review to my web service however I'm having some trouble sending the request it always seems to be failing I'm sure its a simple error I'm over looking but its driving me made.
My Create Review Class is as follows:
-(void)Submit
{
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"https://furious-ice-356.heroku.com/places/%#/reviews.xml",self.identifier]];
//[NSURL URLWithString:[NSString stringWithFormat:#"https://furious-ice-356.heroku.com///places/%#/reviews.xml",self.identifier]];
self.bestnight.text = #"Monday";
ASIFormDataRequest *request1 = [ASIFormDataRequest requestWithURL:url];
[request1 setUsername:self.username];
[request1 setPassword:self.password];
[request1 setRequestMethod:#"POST"];
[request1 setPostValue:self.bestnight.text forKey:#"review[best-night]"];
[request1 setPostValue:self.comments.text forKey:#"review[comments]"];
[request1 setPostValue:self.rating.text forKey:#"review[rating]"];
[request1 setDelegate:self];
[request1 startAsynchronous];
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
}
- (void)requestFinished:(ASIHTTPRequest *)request
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
NSLog(#"FINISH Response received: %#", [request responseString]);
UIAlertView * av = [[[UIAlertView alloc] initWithTitle:#"Thank You" message:#"Your review was successfully posted. Thank You for making our App Better." delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil, nil] autorelease];
[av show];
[self.navigationController popViewControllerAnimated:YES];
}
- (void)requestFailed:(ASIHTTPRequest *)request
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
NSLog(#"FAILED Response received: %#", [request responseString]);
}
Try adding:
[request setShouldPresentCredentialsBeforeChallenge:NO];
Or if that doesn't work, try calling the same but passing 'YES'. Also as others have said double check your username/password.