0

I have a simple form interface set up that send username and password information to a server: (working)

    NSString *postData = [NSString stringWithFormat:@"user=%@&pass=%@",[self urlEncodeValue:sysUsername],[self urlEncodeValue:password]];
NSLog(@"Post data -> %@", postData);
///
NSData* postVariables = [postData dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSMutableURLRequest* request = [[[NSMutableURLRequest alloc] init] autorelease];
NSString* postLength = [NSString stringWithFormat:@"%d", [postVariables length]];
NSURL* postUrl = [NSURL URLWithString:@"http://localhost/~csmith/cocoa/test.php"];
[request setURL:postUrl];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody: postVariables];

NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:NULL error:NULL];
NSLog(@"Post data SENT & returned -> %@", returnData);

How do I handle connection errors such as no internet connection, firewall, etc. Also, does this method use the system-wide proxy settings? Many of my users are behind a proxy.

Thanks a lot!

N S
  • 2,524
  • 6
  • 32
  • 42

2 Answers2

1

First, you shouldn't use synchronous requests, use asynchronous request instead and indicate activity using indeterminate progress indicators.

When using asynchronous requests, you have to set a delegate implement delegate methods, notably:

From the docs:

Unless a NSURLConnection receives a cancel message, the delegate will receive one and only one of connectionDidFinishLoading:, or connection:didFailWithError: message, but never both. In addition, once either of messages are sent, the delegate will receive no further messages for the given NSURLConnection.

As for the last question:

Also, does this method use the system-wide proxy settings?

Yes, NSURLConnection uses them automatically.

Georg Fritzsche
  • 97,545
  • 26
  • 194
  • 236
1

You should use asynchronous request to handle proxy and network errors. This is more efficient. To add extra check you can add reach-ability test in your code before communications. you can find reach-ability test code here

Community
  • 1
  • 1
Unicorn
  • 2,382
  • 6
  • 29
  • 42