完成项目的过程中,需要考虑用户是否有网络连接以及及时的检测网络状态,把用到的判断网络封装的方法分享给大家。
(1)Reachability检测网络状态
.h文件中定义方法...
#import <Foundation/Foundation.h>
#import "Reachability.h"
@interface NetWork : NSObject
+(BOOL)isNetWork;
@end
.m文件
+(BOOL)isNetWork
{
//检测wifi状态
Reachability * wifi = [Reachability reachabilityForLocalWiFi];
//检测手机是否能上网
Reachability * conn = [Reachability reachabilityForInternetConnection];
//判断网络状态
if ([wifi currentReachabilityStatus]!= NotReachable ||[conn currentReachabilityStatus] != NotReachable)
{
return YES;
}
else
{
return NO;
}
}
(2)AFN检测网络
// 网络检测管理者
AFNetworkReachabilityManager *manager=[AFNetworkReachabilityManager sharedManager];
// 开始检测
[manager startMonitoring];
// 设置检测回调
NSUserDefaults *userDefaults=[NSUserDefaults standardUserDefaults];
[manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status)
{
switch (status)
{
case AFNetworkReachabilityStatusUnknown:
[userDefaults setBool:YES forKey:@"isNetWork"];
[userDefaults synchronize];
if (status==AFNetworkReachabilityStatusUnknown)
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提醒" message:@"无网络,请联网" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
[alertView show];
return ;
}
else
{
}
break;
default:
break;
}
}];