IOS开发——网络监测

来源:互联网 发布:拳师七号淘宝店 编辑:程序博客网 时间:2024/06/05 10:28

网络监测

工具下载地址:http://download.csdn.net/detail/u012881779/7020685

编译文件不支持ARC,需要引入支持工具的框架:SystemConfiguration.framework。


interface部分:

#import "Reachability.h"//网络监测@property (strong, nonatomic)Reachability *ymNetwork;

implementation部分:

-(void)viewDidLoad{   [super viewDidLoad];   [self.view setBackgroundColor:[UIColor grayColor]];   //设置通知,网络改变时触发   [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(changeNetwork:) name:kReachabilityChangedNotification object:nil];   //创建Reachability对象   self.ymNetwork = [Reachability reachabilityForInternetConnection];   //开始监听网络   [self.ymNetwork startNotifier];   //获得当前网络   NetworkStatus status = [self.ymNetwork currentReachabilityStatus];   [self checkNetwork:status];}#pragma mark - 网络检测//判断当前是什么网络-(void)checkNetwork:(NetworkStatus)status{   //没有网的时候进行提示   if (status==kNotReachable) {        [self messageBox:@"没有网络"];   }else if (status==kReachableViaWWAN){             [self messageBox:@"正在使用2G/3G网络"];   }else if (status==kReachableViaWiFi){             [self messageBox:@"正在使用wifi网络"];      }}-(void)messageBox:(NSString*)string{   UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"提示"message:string delegate:nil cancelButtonTitle:@"确定"otherButtonTitles:nil,nil];   [alert show];}//网络改变时调用-(void)changeNetwork:(NSNotification*)notification{     //获得当前网络   NetworkStatus status=[self.ymNetwork currentReachabilityStatus];   [self checkNetwork:status];  }


0 0