【问题标题】:Properly handling NSURLConnection errors正确处理 NSURLConnection 错误
【发布时间】:2010-06-07 12:45:10
【问题描述】:

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

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

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

非常感谢!

【问题讨论】:

    标签: objective-c cocoa macos network-programming


    【解决方案1】:

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

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

    来自文档:

    除非 NSURLConnection 收到取消消息,否则委托将收到 connectionDidFinishLoading:connection:didFailWithError: 消息中的一个且只有一个,但绝不会同时收到这两个消息。此外,一旦发送了任何一条消息,代理将不会收到给定 NSURLConnection 的更多消息。

    至于最后一个问题:

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

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

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-11-29
        • 2015-09-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多