iOS网络状态检测
从Git库下载
https://github.com/tonymillion/Reachability
把两个文件Reachability.h 和 Reachability.m文件添加到工程中。
添加框架支持SystemConfiguration.framework
添加头文件声明:
@class Reachability; @interface AppDelegate : UIResponder <UIApplicationDelegate> { UINavigationController *_navigationController; Reachability *hostReach; } @property (strong, nonatomic) UIWindow *window; @property (strong, nonatomic) UIViewController *viewController; @property (strong, nonatomic) UINavigationController *navigationController; @end
AppDelegate.m实现文件中
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 方法中加入如下代码
[self netWorkChecker];
添加网络检测代码
#pragma mark network check -(void)netWorkChecker { hostReach = [Reachability reachabilityWithHostname:@"www.apple.com"]; switch ([hostReach currentReachabilityStatus]) { case NotReachable: NSLog(@"没有网络连接"); // 没有网络连接 break; case ReachableViaWWAN: // 使用3G网络 NSLog(@"使用3G网络"); break; case ReachableViaWiFi: // 使用WiFi网络 NSLog(@"使用WiFi网络"); break; } // }
添加网络变化的通知
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 方法中加入如下代码
[self addNetWorkChangeNotification];
-(void)addNetWorkChangeNotification
{
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(reachabilityChanged:)
name: kReachabilityChangedNotification
object: nil];
hostReach = [Reachability reachabilityWithHostname:@"www.google.com"] ;
[hostReach startNotifier];
}
- (void)reachabilityChanged:(NSNotification *)note
{
Reachability* curReach = [note object];
NSParameterAssert([curReach isKindOfClass: [Reachability class]]);
NetworkStatus status = [curReach currentReachabilityStatus];
NSLog(@"reachabilityChanged delegate NotReachable : %d ", status);
}
浙公网安备 33010602011771号