NSURLConnection error not working - iphone

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.

Related

How to make NSURL connection start transmitting data into dictionary item?

I've got the tagged NSURLConnection subclass, and need to fetch Image data from multiple URL-s...The idea is clear to me, but i can't start the connection properly, so that data would append into its place... here i have:
- (IBAction)sophisticatedDownload {
connectionDict = [[NSMutableDictionary dictionaryWithCapacity:news.count] retain];
for (int i =0; i<news.count; i++)
{
//init the tagged connection
if (theConnection) {
self.imageData = [NSMutableData data];
[connectionDict setObject: imageData forKey: theConnection.connID];
} else {
NSLog(#"Connection failed");
}
}
}
- (void)connection :(tagConnection *)connection didReceiveData:(NSData *)data {
[[connectionDict objectForKey:connection.connID] appendData:data];
}
- (void)connectionDidFinishLoading:(tagConnection *)connection {
NSLog(connection.connID);
What should
You can get start you connection like this -
NSString *urlString = [NSString stringWithFormat:#"http://EnterYourURLHere"];
NSURL *URL = [NSURL URLWithString:urlString];
NSMutableURLRequest *urlRequest = [[NSMutableURLRequest alloc]init];
[urlRequest setURL:URL];
[urlRequest setHTTPMethod:#"POST"];
[urlRequest setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-type"];
NSURLConnection *urlConnection = [[NSURLConnection alloc]initWithRequest:urlRequest delegate:self];
if(!urlConnection)
{
[[[UIAlertView alloc]initWithTitle:#"OOoopppssS !!" message:#"There is an error occured. Please check your internet connection or try again." delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil, nil] show];
}
But this is not good approach to download multiple images. See NSURLConnection Download multiple images to download multiple images.

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
}

"Operation couldn't be completed. Connection reset by peer." with NSURLConnection on iOS

I'm struggling sending POST data to a server and receiving the correct response. I started by using setHTTPBody but moved to setHTTPBodyStream when I wasn't getting the correct server response for certain POST data and I read setHTTPBody has a memory leak on earlier iOS versions. The problem is setHTTPBodyStream causes the error - "Operation couldn't be completed. Connection reset by peer".
Here's the code:
NSMutableURLRequest * request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"secret but correct url goes here"] cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:10.0];
[request setHTTPMethod: #"POST"];
[request setHTTPBodyStream: [NSInputStream inputStreamWithData: [[NSString stringWithFormat:#"username=%#&password=%#&score=%i",[(NSString*)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)ogl_view->username, NULL, CFSTR("?=&+"), kCFStringEncodingUTF8) autorelease],[(NSString*)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)text_field.text, NULL, CFSTR("?=&+"), kCFStringEncodingUTF8) autorelease],ogl_view->score[0]] dataUsingEncoding:NSUnicodeStringEncoding]]];
NSURLConnection * connection = [[NSURLConnection alloc] initWithRequest: request delegate:self];
if (connection){
received_data = [[NSMutableData data] retain];
ogl_view->section = CURLING_PROCESS_CREDENTIALS;
}else{
ogl_view->section = CURLING_LOGIN_OR_REGISTER;
UIAlertView *connection_alert = [[UIAlertView alloc] initWithTitle:#"Error" message: #"Can't connect to server" delegate:self cancelButtonTitle:#"Close" otherButtonTitles: nil];
[connection_alert show];
[connection_alert release];
}
I can verify the server is fine and it works when I try a web-browser.
Can somebody get me on the right track to sending data with HTTP and the POST method correctly?
Thank you for any help.
Try using this (with your own values):
NSString* post = #"username=myUser&password=myPass&score=20"; //customize this
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
NSURL *url = [NSURL URLWithString:#"http://my.request.com"]; //customize this
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
[request setTimeoutInterval:timeout];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
You'll then need to implement the NSURLConnectionDelegate methods:
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response;
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)remoteData;
- (void)connectionDidFinishLoading:(NSURLConnection *)connection;
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error;
In the end, remember to release the NSURLConnection.
Edit: Didn't see that you wrote that setHTTPBody leaks... never seen that happening. Anyway, here is some code that should work...

NSMutableURLRequest and a Password with special Characters won't work

I'm writing a small program (using Cocoa Touch), which communicates with a webservice.
The code for calling the webservice, is the following:
- (IBAction)send:(id)sender
{
if ([number.text length] > 0)
{
[[UIApplication sharedApplication] beginIgnoringInteractionEvents];
[activityIndicator startAnimating];
NSString *modded;
modded = [self computeNumber];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL: [NSURL URLWithString:#"https://tester:%=&=-Test2009#samurai.sipgate.net/RPC2"]];
[theRequest setHTTPMethod:#"POST"];
[theRequest addValue:#"text/xml" forHTTPHeaderField:#"content-type"];
[theRequest setCachePolicy:NSURLCacheStorageNotAllowed];
[theRequest setTimeoutInterval:5.0];
NSString* pStr = [[NSString alloc] initWithFormat:#"<?xml version=\"1.0\" encoding=\"UTF-8\"?><methodCall><methodName>samurai.SessionInitiate</methodName><params><param><value><struct><member><name>LocalUri</name><value><string></string></value></member><member><name>RemoteUri</name><value><string>sip:%##sipgate.net</string></value></member><member><name>TOS</name><value><string>text</string></value></member><member><name>Content</name><value><string>%#</string></value></member><member><name>Schedule</name><value><string></string></value></member></struct></value></param></params></methodCall>", modded, TextView.text];
NSData* pBody = [pStr dataUsingEncoding:NSUTF8StringEncoding];
[theRequest setHTTPBody:pBody];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if (!theConnection)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error"
message:#"A Connection could not be established!"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles: nil];
[alert show];
[alert release];
sendButton.enabled = TRUE;
return;
}
[pStr release];
[pBody release];
}
}
The Username and Password have to be in the URL, and it works in most cases, but when the password consists of special characters like in the example "%=&=-Test2009", the Webservice does not respond. If it is something like "Test2009" it works fine. Does anyone have an idea why, and maybe a solution for that?
Special characters have to be URL encoded, the URL you requested,
https://tester:%=&=-Test2009#samurai.sipgate.net/RPC2
..is invalid, specifically the %= part (% is used for escaping characters, for example %20 is used to represent a space), so..
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:
[NSURL URLWithString:#"https://tester:%=&=-Test2009#samurai.sipgate.net/RPC2"]];
..should change to something like:
NSString *theAddress = [NSString stringWithFormat:#"https://%#:%##%#",
[#"tester" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
[#"%=&=-Test2009" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding],
#"example.com"];
NSURL *theURL = [NSURL URLWithString:theAddress];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:theURL];
This requests the URL https://tester:%25=&=-Test2009#example.com
You must use URL safe characters in your string when making the URL, use this NSString method stringByAddingPercentEscapesUsingEncoding: which will do this for you.