正确处理NSURLConnection错误

时间:2010-06-07 12:45:11

标签: objective-c cocoa macos network-programming

我有一个简单的表单界面设置,可以将用户名和密码信息发送到服务器:(工作)

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

如何处理连接错误,例如没有互联网连接,防火墙等。 此外,此方法是否使用系统范围的代理设置?我的许多用户都在代理服务器后面。

非常感谢!

2 个答案:

答案 0 :(得分:1)

首先,您不应使用同步请求,而是使用异步请求并使用indeterminate progress indicators指示活动。

使用异步请求时,您必须设置委托实现delegate methods,特别是:

来自文档:

  

除非NSURLConnection收到取消消息,否则代理人将收到connectionDidFinishLoading:connection:didFailWithError:消息中的一个,但不会同时收到两个消息。此外,一旦发送了任一消息,代理将不再接收给定NSURLConnection的消息。

关于最后一个问题:

  

此外,此方法是否使用系统范围的代理设置?

是的,NSURLConnection会自动使用它们。

答案 1 :(得分:1)

您应该使用异步请求来处理代理和网络错误。这更有效率。 要添加额外的检查,您可以在通信之前在代码中添加可达性测试。你可以找到可达性测试代码here