您的位置:首页 > 理论基础 > 计算机网络

iOS使用Reachability监听网络状态

2015-09-09 14:56 567 查看
1. 参考文章:点击打开链接

2. 具体使用:

2.1 导入SystemConfiguration.framework

2.2 我在Reachability添加了三个静态方法,用于判断网络状态

#pragma mark ------add by liuming @2015.9.9--------
// 是否wifi
+ (BOOL) IsEnableWIFI;

// 是否234G:优先使用wifi。wifi连接状态下,即使3G流量是打开的,系统会使用wifi,因此返回NO
+ (BOOL) IsEnable3G;

//Host是否畅通,与IsEnableInternet效果一致[Host必须是正确的]
+ (BOOL) IsEnableHost:(NSString *)host;

//网络是否畅通,3G,wifi两项有一项畅通即返回YES
+ (BOOL) IsEnableInternet;


2.3 ViewController代码:

//
//  ViewController.m
//  Demo_网络监测
//
//  Created by liuming on 15/9/9.
//  Copyright (c) 2015年 makeblock. All rights reserved.
//

#import "ViewController.h"
#import "Reachability.h"

#define HOST (@"www.google.com.hk")
@interface ViewController ()

@property (nonatomic) Reachability *hostReachability;
@property (nonatomic) Reachability *internetReachability;
@property (nonatomic) Reachability *wifiReachability;

@end

@implementation ViewController

- (void)checkNetwork {
if ([Reachability IsEnableWIFI]) {
NSLog(@"## WIFI Connected");
}else{
NSLog(@"## WIFI Disconnected");
}

if ([Reachability IsEnable3G]) {
NSLog(@"## 3G Connected");
}else{
NSLog(@"## 3G Disconnected");
}

if ([Reachability IsEnableHost:HOST]) {
NSLog(@"## Host Connected");
}else{
NSLog(@"## Host Disconnected");
}

if ([Reachability IsEnableInternet]) {
NSLog(@"## Internet Connected");
}else{
NSLog(@"## Internet Disconnected");
}
}

- (void)viewDidLoad {
[super viewDidLoad];
NSLog(@"---------viewDidLoad-----------");
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];

self.hostReachability = [Reachability reachabilityWithHostName:HOST];
[self.hostReachability startNotifier];

self.internetReachability = [Reachability reachabilityForInternetConnection];
[self.internetReachability startNotifier];

self.wifiReachability = [Reachability reachabilityForLocalWiFi];
[self.wifiReachability startNotifier];

//这么写是不行的,Reachability会被dealloc,就无法监听到网络状态的变化了
//    [[Reachability reachabilityWithHostName:HOST] startNotifier];
//    [[Reachability reachabilityForInternetConnection] startNotifier];
//    [[Reachability reachabilityForLocalWiFi] startNotifier];

[self checkNetwork];
}

/*!
* Called by Reachability whenever status changes.
*/
- (void) reachabilityChanged:(NSNotification *)note {\
NSLog(@"-----------reachabilityChanged-----------");
Reachability* curReach = [note object];
NSParameterAssert([curReach isKindOfClass:[Reachability class]]);
[self checkNetwork];
}

@end


2.4 demo链接:http://pan.baidu.com/s/1i32Hodn
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: