基于AFNetworking的网络判断【原创】

首先导入AFNetworking第三方框架,然后将下面的.h和.m放在你新建的类中便可

GGNetworkJudge.h   在最后会有Singleton.h头文件代码

 #import <Foundation/Foundation.h>
#import "AFNetworkReachabilityManager.h"
#import "Singleton.h" //此处是将一个普通类转化为单例类的头文件 @interface GGNetworkJudge : NSObject singleton_interface(GGNetworkJudge); //监测网络状态
- (void)checkNetworkStatus; @end

GGNetworkJudge.m

 #import "GGNetworkJudge.h"
#import <UIKit/UIKit.h> @implementation GGNetworkJudge
singleton_implementation(GGNetworkJudge); #pragma mark - 私有方法
#pragma mark 网络状态变化提示
-(void)alert:(NSString *)message{
UIAlertView *alertView=[[UIAlertView alloc]initWithTitle:@"系统信息" message:message delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
[alertView show];
} #pragma mark 网络状态监测
-(void)checkNetworkStatus{ AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager]; //开始监控
[manager startMonitoring]; // 检测网络连接的单例,网络变化时的回调方法
[manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) { switch (status) {
case AFNetworkReachabilityStatusReachableViaWWAN:
//[self alert:@"2G/3G/4G Connection."];
[self alert:@"网络已连接"]; break;
case AFNetworkReachabilityStatusReachableViaWiFi:
// [self alert:@"WiFi Connection."]; [self alert:@"网络已连接"];
break;
case AFNetworkReachabilityStatusNotReachable:
// [self alert:@"Network not found."];
[self alert:@"网络已断开,请检查网络设置"]; break; default:
// [self alert:@"Unknown."];
[self alert:@"网络未知错误"]; break; } }]; } @end

Singleton.h

 /*
专门用来保存单例代码
最后一行不要加 \
*/ // @interface
#define singleton_interface(className) \
+ (className *)shared##className; // @implementation
#define singleton_implementation(className) \
static className *_instance; \
+ (id)allocWithZone:(NSZone *)zone \
{ \
static dispatch_once_t onceToken; \
dispatch_once(&onceToken, ^{ \
_instance = [super allocWithZone:zone]; \
}); \
return _instance; \
} \
+ (className *)shared##className \
{ \
static dispatch_once_t onceToken; \
dispatch_once(&onceToken, ^{ \
_instance = [[self alloc] init]; \
}); \
return _instance; \
}
上一篇:09 Finding a Motif in DNA


下一篇:Centos系统mysql 忘记root用户的密码