有没有人找到了一个相当不错的 iOS Reachability 实现指南?
我已经按照如下方式实现了 Reachability。
下载 https://developer.apple.com/library/content/samplecode/Reachability/Introduction/Intro.html 并将 Reachability.h 和 .m 添加到您的项目中。将 SystemConfiguration 框架添加到您的项目中。在您想使用它的地方添加 #import "Reachability.h"。使用以下代码。
-(BOOL)reachable {
Reachability *r = [Reachability reachabilityWithHostName:@"enbr.co.cc"];
NetworkStatus internetStatus = [r currentReachabilityStatus];
if(internetStatus == NotReachable) {
return NO;
}
return YES;
}
当您想要检查可达性时...
if ([self reachable]) {
NSLog(@"Reachable");
}
else {
NSLog(@"Not Reachable");
}
这是我制作的示例项目。 http://dl.dropbox.com/u/3656129/ReachabilityExample.zip
我认为检查主机地址可用性的最佳方法是通过检查NSURL请求的结果。
NSURLRequest *theRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:reqURL]];
NSURLResponse *resp = nil;
NSError *error = nil;
NSData *response = [NSURLConnection sendSynchronousRequest: theRequest returningResponse: &resp error: &error];
NSString *responseString = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];