导入这两个文件先
Reachability.hReachability.m
//
// ViewController.m
// AppleReachablity
//
// Created by hq on 16/4/18.
// Copyright © 2016年 hanqing. All rights reserved.
//
#import "ViewController.h"
#import "Reachability.h"
@interface ViewController ()
@property(nonatomic,strong) Reachability *ablity;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self monitorNetWork];
}
//监听网络的变化
-(void) monitorNetWork{
NSNotificationCenter *notification=[NSNotificationCenter defaultCenter];
//让我们的netWorkChanged方法监听网络状态的变化
[notification addObserver:self selector:@selector(netWorkChanged) name:kReachabilityChangedNotification object:nil];
self.ablity=[Reachability reachabilityForInternetConnection];
[self.ablity startNotifier];
}
-(void) netWorkChanged{
//NotReachable = 0,
//ReachableViaWiFi,
//ReachableViaWWAN
if (self.ablity.currentReachabilityStatus==NotReachable) {
NSLog(@"未连接网络");
}
else if(self.ablity.currentReachabilityStatus==ReachableViaWiFi){
NSLog(@"当前网络为wifi");
}
else{
NSLog(@"手机自带网络");
}
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
本文介绍了一个iOS应用中实现网络状态监测的方法。通过Reachability类,可以实时获取设备的网络连接状态,包括未连接网络、WiFi连接和手机数据网络连接,并在状态改变时通知应用程序进行相应的处理。
1092

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



