Objective c 如何使用可达性类检测有效的internet连接?
我是iOS开发新手,正在努力让可达性.h类正常工作。以下是我的视图控制器代码:Objective c 如何使用可达性类检测有效的internet连接?,objective-c,ios,ios4,reachability,Objective C,Ios,Ios4,Reachability,我是iOS开发新手,正在努力让可达性.h类正常工作。以下是我的视图控制器代码: - (void)viewWillAppear:(BOOL)animated { [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkNetworkStatus:) name:kReachabilityChangedNotification object:nil
- (void)viewWillAppear:(BOOL)animated
{
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(checkNetworkStatus:)
name:kReachabilityChangedNotification
object:nil];
internetReachable = [Reachability reachabilityForInternetConnection];
[internetReachable startNotifier];
}
- (void)checkNetworkStatus:(NSNotification *)notice {
NetworkStatus internetStatus = [internetReachable currentReachabilityStatus];
NSLog(@"Network status: %i", internetStatus);
}
它看起来不错,但在运行应用程序并切换到该视图时,xcode控制台中没有显示任何内容
我正在使用可达性2.2和iOS 4.2
有什么明显的错误吗?编辑:如果您想在执行某些代码之前检查可达性,您应该使用
Reachability *reachability = [Reachability reachabilityForInternetConnection];
NetworkStatus internetStatus = [reachability currentReachabilityStatus];
if (internetStatus != NotReachable) {
//my web-dependent code
}
else {
//there-is-no-connection warning
}
您还可以在某处添加可达性观察者(即在viewDidLoad
中):
不要忘记调用
[[NSNotificationCenter defaultCenter]removeObserver:self]代码>当您不再需要可达性检测时(即在dealloc
方法中)。以下是我的操作方法。我在init方法中设置了一个实例变量:
_reachability = [[APReachability reachabilityForInternetConnection] retain];
当我需要查询网络状态时,我会:
NetworkStatus networkStatus = [_reachability currentReachabilityStatus];
if (networkStatus != NotReachable) {
// Network related code
}
else {
// No network code
}
如果您关心wifi等,网络状态可以是:
NotReachable // No network
ReachableViaWiFi // Reachable via Wifi
ReachableViaWWAN // Reachable via cellular
更新:2013年11月4日
在iOS7上使用可达性3.0版本
要在@NR4TR和@codecaffine的答案之上构建:
有5种方法可以做到这一点(未编译:)
只需导入可达性类,然后
-(BOOL) connectedToNetwork
{
const char *host_name = "www.google.com";
BOOL _isDataSourceAvailable = NO;
Boolean success;
SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithName(NULL,host_name);
SCNetworkReachabilityFlags flags;
success = SCNetworkReachabilityGetFlags(reachability, &flags);
_isDataSourceAvailable = success &&
(flags & kSCNetworkFlagsReachable) &&
!(flags & kSCNetworkFlagsConnectionRequired);
CFRelease(reachability);
return _isDataSourceAvailable;
}
请参阅下面的代码以检查互联网连接:
struct sockaddr_in zeroAddress;
bzero(&zeroAddress, sizeof(zeroAddress));
zeroAddress.sin_len = sizeof(zeroAddress);
zeroAddress.sin_family = AF_INET;
// Recover reachability flags
SCNetworkReachabilityRef defaultRouteReachability = SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr*)&zeroAddress);
SCNetworkReachabilityFlags flags;
BOOL didRetrieveFlags = SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags);
CFRelease(defaultRouteReachability);
if (!didRetrieveFlags) {
return 0;
}
BOOL isReachable = flags & kSCNetworkFlagsReachable;
BOOL needsConnection = flags & kSCNetworkFlagsConnectionRequired;
BOOL nonWiFi = flags & kSCNetworkReachabilityFlagsTransientConnection;
NSURL *testURL = [NSURL URLWithString:@"http://www.google.com/"];
NSURLRequest *testRequest = [NSURLRequest requestWithURL:testURL cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:20.0];
NSURLResponse *response = nil;
NSError *error = nil;
NSData *connectiondata = [NSURLConnection sendSynchronousRequest:testRequest
returningResponse:&response
BOOL connection=NO;
if ([connectiondata length] > 0 &&
error == nil){
NSLog(@"Connection present” );
connection=YES;
} else {
NSLog(@"No Connection" );
connection=NO;
}
return ((isReachable && !needsConnection) || nonWiFi) ? (connection ? YES : NO) : NO;
遵循这个链接,它有非常有用的源代码和步骤
.
这为您提供了有关如何在可达性中使用不同方法的信息
添加system.configuration.framewok,并将Reachability.m和Reachability.h文件添加到项目中。有使用后的方法,如
+(instancetype)reachabilityWithHostName:(NSString*)hostname;
+(instancetype)reachabilityForInternetConnection;
+(instancetype)reachabilityWithAddress:(void *)hostAddress;
+(instancetype)reachabilityForLocalWiFi;
示例代码段:
- (void)CheckConnection
{
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(reachabilityChanged:)
name:kReachabilityChangedNotification
object:nil];
Reachability * reach = [Reachability reachabilityWithHostname:@"www.google.com"];
reach.reachableBlock = ^(Reachability * reachability)
{
dispatch_async(dispatch_get_main_queue(), ^{
_blockLabel.stringValue = @"Block Says Reachable";
});
};
reach.unreachableBlock = ^(Reachability * reachability)
{
dispatch_async(dispatch_get_main_queue(), ^{
_blockLabel.stringValue = @"Block Says Unreachable";
});
};
[reach startNotifier];
}
希望这有助于最简单的方法(一旦添加到项目中):
感谢您的帮助,但我收到一个错误消息-isReachable未找到。你的例子是旧版本的可达性吗?这可能会引起很大的麻烦。按需VPN连接和其他有问题的东西怎么样?当然这不是必须的,但我无法想象没有任何可达性的使用,好的web服务相关应用程序
struct sockaddr_in zeroAddress;
bzero(&zeroAddress, sizeof(zeroAddress));
zeroAddress.sin_len = sizeof(zeroAddress);
zeroAddress.sin_family = AF_INET;
// Recover reachability flags
SCNetworkReachabilityRef defaultRouteReachability = SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr*)&zeroAddress);
SCNetworkReachabilityFlags flags;
BOOL didRetrieveFlags = SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags);
CFRelease(defaultRouteReachability);
if (!didRetrieveFlags) {
return 0;
}
BOOL isReachable = flags & kSCNetworkFlagsReachable;
BOOL needsConnection = flags & kSCNetworkFlagsConnectionRequired;
BOOL nonWiFi = flags & kSCNetworkReachabilityFlagsTransientConnection;
NSURL *testURL = [NSURL URLWithString:@"http://www.google.com/"];
NSURLRequest *testRequest = [NSURLRequest requestWithURL:testURL cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:20.0];
NSURLResponse *response = nil;
NSError *error = nil;
NSData *connectiondata = [NSURLConnection sendSynchronousRequest:testRequest
returningResponse:&response
BOOL connection=NO;
if ([connectiondata length] > 0 &&
error == nil){
NSLog(@"Connection present” );
connection=YES;
} else {
NSLog(@"No Connection" );
connection=NO;
}
return ((isReachable && !needsConnection) || nonWiFi) ? (connection ? YES : NO) : NO;
+(instancetype)reachabilityWithHostName:(NSString*)hostname;
+(instancetype)reachabilityForInternetConnection;
+(instancetype)reachabilityWithAddress:(void *)hostAddress;
+(instancetype)reachabilityForLocalWiFi;
- (void)CheckConnection
{
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(reachabilityChanged:)
name:kReachabilityChangedNotification
object:nil];
Reachability * reach = [Reachability reachabilityWithHostname:@"www.google.com"];
reach.reachableBlock = ^(Reachability * reachability)
{
dispatch_async(dispatch_get_main_queue(), ^{
_blockLabel.stringValue = @"Block Says Reachable";
});
};
reach.unreachableBlock = ^(Reachability * reachability)
{
dispatch_async(dispatch_get_main_queue(), ^{
_blockLabel.stringValue = @"Block Says Unreachable";
});
};
[reach startNotifier];
}
Reachability *reachability = [Reachability reachabilityForInternetConnection];
if (reachability.isReachable) {
NSLog(@"We have internet!");
} else {
NSLog(@"No internet!");
}