3

我使用NSString方法initWithContentsOfURL:usedEncoding:error:来获取某些页面的内容。我注意到,当我尝试访问的页面不存在时,此方法会执行很长时间,然后因超时错误而失败。我尝试出于相同的目的使用NSURLRequestNSURLConnection类,但得到相同的结果 - 执行时间长然后超时错误。当我尝试在浏览器中打开同一页面时,我会更快地得到响应并返回页面不可用错误。

看起来可可方法不对页面名称进行 dns 解析,或者它们对该操作有更长的超时时间。

所以我的问题是,我使用的可可方法可以解析 dns 吗?如果他们不这样做怎么办?

我使用的代码示例:

NSURL* url = [NSURL URLWithString:@"http://unexisting.domain.local"]; 
NSError* err = nil;
NSString* content = [NSString stringWithContentsOfURL:url usedEncoding:nil error:&err];

if (err) {
    NSLog(@"error: %@", err); 
} else {
    NSLog(@"content: %@", content);
}

NSURL* url = [NSURL URLWithString:@"http://unexisting.domain.local"]; 
NSURLRequest* request = [NSURLRequest requestWithURL:url];

NSURLResponse* response = nil;
NSError* err = nil;
NSData* data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];

if (err) {
    NSLog(@"error: %@", err); 
} else {
    NSString* content = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"content: %@", content);
}

谢谢!

4

2 回答 2

0

Gene M.回答了如何使用 of 来做到这一点SCNetworkReachability。这是示例代码:

bool success = false;
const char *host_name = [@"stackoverflow.com" 
                         cStringUsingEncoding:NSASCIIStringEncoding];

SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithName(NULL,
                                                                        host_name);
SCNetworkReachabilityFlags flags;
success = SCNetworkReachabilityGetFlags(reachability, &flags);
bool isAvailable = success && (flags & kSCNetworkFlagsReachable) && 
                             !(flags & kSCNetworkFlagsConnectionRequired);
if (isAvailable) {
    NSLog(@"Host is reachable: %d", flags);
}else{
    NSLog(@"Host is unreachable");
}
于 2012-12-19T18:28:00.113 回答
0

监控可达性(设备连接性)并对其做出反应绝对是一种很好的做法,如上所述。

您还可以实现NSURLConnectionDelegate协议及其方法,例如

 - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
      NSLog(@"**ERROR** %@", error);
      // Respond to error
 }

如果你没有连接,你应该得到一个 NSURLConnection 错误代码 999 和NSURLErrorCancelled = -999/或NSURLErrorNotConnectedToInternet = -1009如果你没有连接,等等。至少你会有一个关于正在发生的事情的报告。

文档: https ://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_Constants/Reference/reference.html

于 2012-12-19T18:42:44.207 回答