开发者

Properly handling NSURLConnection errors

开发者 https://www.devze.com 2023-01-02 08:02 出处:网络
I have a simple form interface set up that send username and password information to a server: (working开发者_Python百科)

I have a simple form interface set up that send username and password information to a server: (working开发者_Python百科)

    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!


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:

  • -connectionDidFinishLoading:
  • -connection:didFailWithError:

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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号