最近的项目中有的地方需要判断网络连接
参考 Reachability 文件 并进一步封装 现在把代码放到网上 大家可以做一个参考
导入 Reachability.h / .m 时记得导入 systemconfiguration.framework
这是Reachability 和 Network的下载地址: 下载文件包
JPNetwork.h
#import <Foundation/Foundation.h>
@interface JPNetwork : NSObject
/**
* @brief get the signalton engine object
* @return the engine object
*/
+ (JPNetwork *)sharedInstance;
/**
* @brief get the network statue
*/
- (BOOL)isNetworkReachable;
/**
* @brief Judgment wifi is connected
*/
- (BOOL)isEnableWIFI;
/**
* @brief To judge whether the 3G connection
*/
- (BOOL)isEnable3G;
+ (BOOL)isNetworkContected;
+ (void)networkBreak;
@end
JPNetwork.m
#import "JPNetwork.h"
#import "Reachability.h"
@implementation JPNetwork
static JPNetwork *g_instance = nil;
- (id)init
{
self = [super init];
if (self) {
}
return self;
}
/**
* @brief Whether there are single instance
* @return the result
*/
+ (BOOL)sharedInstanceExists
{
return (nil != g_instance);
}
/**
* @brief get the signalton engine object
* @return the engine object
*/
+ (JPNetwork *)sharedInstance
{
@synchronized(self) {
if ( g_instance == nil ) {
g_instance = [[[self class] alloc] init];
//any other specail init as required
}
}
return g_instance;
}
/**
* @brief get the network statue
*/
- (BOOL)isNetworkReachable
{
BOOL isReachable = NO;
Reachability *reachability = [Reachability reachabilityWithHostName:@"www.baidu.com"];
switch ([reachability currentReachabilityStatus]) {
case NotReachable:{
isReachable = NO;
}
break;
case ReachableViaWWAN:{
isReachable = YES;
}
break;
case ReachableViaWiFi:{
isReachable = YES;
}
break;
default:
isReachable = NO;
break;
}
return isReachable;
}
/**
* @brief Judgment wifi is connected
*/
- (BOOL)isEnableWIFI
{
return ([[Reachability reachabilityForLocalWiFi] currentReachabilityStatus] != NotReachable);
}
/**
* @brief To judge whether the 3G connection
*/
- (BOOL)isEnable3G
{
return ([[Reachability reachabilityForInternetConnection] currentReachabilityStatus] != NotReachable);
}
+ (BOOL)isNetworkContected
{
return [[JPNetwork sharedInstance] isNetworkReachable];
}
+ (void)networkBreak
{
UIAlertView *alter = [[UIAlertView alloc]initWithTitle:@"温馨提示" message:@"哎呦喂、网络不给力啊" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
[alter show];
[alter release];
}
@end
在工程中导入JPNetwork.h 之后
在需要判断网络连接状态的地方
if ([JPNetwork isNetworkContected] )
{
//网络连接正常
}else{
//无网络连接
[JPNetwork networkBreak];
}