我目前正在使用以下方法检查viewDidLoad
上的网络连接:
-(BOOL)reachable {
ReachabilityDRC *r = [ReachabilityDRC reachabilityWithHostName:@"google.com"];
NetworkStatus internetStatus = [r currentReachabilityStatus];
if(internetStatus == NotReachable) {
return NO;
}
return YES;
}
但我也希望在网络发生变化时收到通知,例如wifi掉线或wifi恢复,所以我可以相应地进行更改。
如何调整方法以执行类似的操作?
答案 0 :(得分:9)
1-将SystemConfiguration.framework
添加到您的项目中。
2-从GitHub
下载以下文件Reachability.h
Reachability.m
3-在项目中添加这些文件
4-在@class Reachability;
YourViewController.h
#import <UIKit/UIKit.h>
@class Reachability;
5-在Reachability* internetReachable;
YourViewController.h
#import <UIKit/UIKit.h>
@class Reachability;
@interface YourViewController : UIViewController {
Reachability* internetReachable;
}
6-在Reachability.h
YourViewController.m
#import "YourViewController.h"
#import "Reachability.h"
7-在-(void)ViewDidLoad
YourViewController.m
添加以下行
-(void)ViewDidLoad {
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(checkNetworkStatus:)
name:kReachabilityChangedNotification
object:nil];
internetReachable = [Reachability reachabilityForInternetConnection];
[internetReachable startNotifier];
}
8-在-(void)viewDidLoad
-(void) checkNetworkStatus:(NSNotification *)notice
{
// called after network status changes
NetworkStatus internetStatus = [internetReachable currentReachabilityStatus];
switch (internetStatus)
{
case NotReachable:
{
NSLog(@"The internet is down.");
break;
}
case ReachableViaWiFi:
{
NSLog(@"The internet is working via WIFI.");
break;
}
case ReachableViaWWAN:
{
NSLog(@"The internet is working via WWAN.");
break;
}
}
}
现在,每次更改互联网连接都会看到登录控制台。
答案 1 :(得分:6)
另一种可能的解决方案是在“application didfinishlaunching”中添加NS Notification:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(checkForReachability) name:kReachabilityChangedNotification object:nil];
并在checkForReachability方法中执行此操作:
Reachability *reachability = [Reachability reachabilityForInternetConnection];
[reachability startNotifier];
NetworkStatus remoteHostStatus = [reachability currentReachabilityStatus];
if(remoteHostStatus == NotReachable) {
//Do something
}
else if (remoteHostStatus == ReachableViaWiFi) {
// Do something
}
else{
// Else do something else
}
答案 2 :(得分:0)
我使用了Donoho Design Group所组合的Reachability类的优秀扩展。它具有通知,允许您在网络状态更改时收到警报。
祝你好运