添加第三方Reachability 加入需要添加Systemconfiguration.framework
#import"AppDelegate.h"
在didFinishLaunchingWithOptions中添加
/****************************************************/
//网络检测****************
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name: kReachabilityChangedNotification object: nil];
hostReach = [Reachability reachabilityWithHostName:@"www.baidu.com"];
[hostReach startNotifier];
/****************************************************/
- (void)reachabilityChanged:(NSNotification*)note{
NSLog(@"==_==");
Reachability* curReach= [note object];
NSParameterAssert([curReach isKindOfClass: [Reachability class]]);
[self updateInterfaceWithReachability:curReach];
}
// 更新网络状态
- (void)updateInterfaceWithReachability: (Reachability*)curReach
{
//对连接改变做出响应的处理动作。
NetworkStatus status=[curReach currentReachabilityStatus];
NSUserDefaults * user =[NSUserDefaults standardUserDefaults];
if (status== NotReachable) { //没有连接到网络就弹出提实况
[user removeObjectForKey:@"network"];
[user setBool:NO forKey:@"network"];
[self showAlert:@"网络连接被断开"];
}else{
[user removeObjectForKey:@"network"];
[user setBool:YES forKey:@"network"];
[self showAlert:@"网络连接成功"];
}
NSLog(@"%@",[user objectForKey:@"network"]);
[[NSNotificationCenter defaultCenter]postNotificationName:@"network" object:user];
}
-(void)showAlert:(NSString *)message{
UIAlertView*alert= [[UIAlertView alloc] initWithTitle:message
message:nil delegate:nil
cancelButtonTitle:@"确定"otherButtonTitles:nil];
[alert show];
}
#import"ViewController.h"
在此viewDidLoad中添加注册通知
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(network:) name:@"network" object:nil];
}-(void)network:(NSNotification *)note{
id obj = [note object];//获取到传递的对象
NSLog(@"---%@-----",[obj objectForKey:@"network"]);
BOOL isOpen = [[obj objectForKey:@"network"] intValue];
NSLog(@"%d",isOpen);
if (isOpen) {
NSLog(@"--有网络--");
}else{
NSLog(@"--无网络--");
}
}最近学会的一个怎么实现网络实时监控的简易方法。欢迎大家能指出其中不恰当的地方。
849

被折叠的 条评论
为什么被折叠?



