基于AFNetworking的网络判断【原创】
首先导入AFNetworking第三方框架,然后将下面的.h和.m放在你新建的类中便可
GGNetworkJudge.h 在最后会有Singleton.h头文件代码
1 #import <Foundation/Foundation.h> 2 #import "AFNetworkReachabilityManager.h" 3 #import "Singleton.h" //此处是将一个普通类转化为单例类的头文件 4 5 @interface GGNetworkJudge : NSObject 6 7 singleton_interface(GGNetworkJudge); 10 11 //监测网络状态 12 - (void)checkNetworkStatus; 13 14 @end
GGNetworkJudge.m
1 #import "GGNetworkJudge.h" 2 #import <UIKit/UIKit.h> 3 4 @implementation GGNetworkJudge 5 singleton_implementation(GGNetworkJudge); 6 7 #pragma mark - 私有方法 8 #pragma mark 网络状态变化提示 9 -(void)alert:(NSString *)message{ 10 UIAlertView *alertView=[[UIAlertView alloc]initWithTitle:@"系统信息" message:message delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil]; 11 [alertView show]; 12 } 13 14 #pragma mark 网络状态监测 15 -(void)checkNetworkStatus{ 16 17 AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager]; 18 19 //开始监控 20 [manager startMonitoring]; 21 22 23 // 检测网络连接的单例,网络变化时的回调方法 24 [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) { 25 26 switch (status) { 27 case AFNetworkReachabilityStatusReachableViaWWAN: 28 //[self alert:@"2G/3G/4G Connection."]; 29 [self alert:@"网络已连接"]; 30 31 break; 32 case AFNetworkReachabilityStatusReachableViaWiFi: 33 // [self alert:@"WiFi Connection."]; 34 35 [self alert:@"网络已连接"]; 36 break; 37 case AFNetworkReachabilityStatusNotReachable: 38 // [self alert:@"Network not found."]; 39 [self alert:@"网络已断开,请检查网络设置"]; 40 41 42 break; 43 44 default: 45 // [self alert:@"Unknown."]; 46 [self alert:@"网络未知错误"]; 47 48 break; 49 50 } 51 52 }]; 53 54 55 56 57 58 } 59 60 61 @end
Singleton.h
1 /* 2 专门用来保存单例代码 3 最后一行不要加 \ 4 */ 5 6 // @interface 7 #define singleton_interface(className) \ 8 + (className *)shared##className; 9 10 11 // @implementation 12 #define singleton_implementation(className) \ 13 static className *_instance; \ 14 + (id)allocWithZone:(NSZone *)zone \ 15 { \ 16 static dispatch_once_t onceToken; \ 17 dispatch_once(&onceToken, ^{ \ 18 _instance = [super allocWithZone:zone]; \ 19 }); \ 20 return _instance; \ 21 } \ 22 + (className *)shared##className \ 23 { \ 24 static dispatch_once_t onceToken; \ 25 dispatch_once(&onceToken, ^{ \ 26 _instance = [[self alloc] init]; \ 27 }); \ 28 return _instance; \ 29 }