在日常的app开发中,我们会根据网络的不同状态,做不同的事情,也会当网络断开时,给弹出框提示,这样更好的提醒用户当前的网络状态,避免用户浪费流量,也增加用户的使用舒服感.
在开发过程中,我们一般使用AFNetworking这个三方库请求接口数据,下面我想分享的是使用AFNetworking在appDelegate.m中写个方法直接实时监测网络状态,并获得断网之后的提示,很简单的代码,只需要复制粘贴即可,本人已经测试过了
在AppDelegate.m中引用头文件
import "AFNetworking.h"
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
....
[self networkingState];
....
return YES;
}
- (void)networkingState {
[[AFNetworkReachabilityManager sharedManager] startMonitoring];
[[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
switch (status) {
case -1:
NSLog(@"未知网络");
break;
case 0:
NSLog(@"网络不可达");
break;
case 1:
NSLog(@"GPRS网络");
break;
case 2:
NSLog(@"wifi网络");
break;
default:
break;
}
if(status ==AFNetworkReachabilityStatusReachableViaWWAN || status == AFNetworkReachabilityStatusReachableViaWiFi)
{
NSLog(@"有网");
} else {
NSLog(@"没有网");
UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"网络失去连接" message:nil preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
}];
[alertVC addAction:cancelAction];
//初始化UIWindows
UIWindow *AW = [[UIWindow alloc]initWithFrame:[UIScreen mainScreen].bounds];
AW.rootViewController = [[UIViewController alloc]init];
AW.windowLevel = UIWindowLevelAlert + 1;
[AW makeKeyAndVisible];
[AW.rootViewController presentViewController:alertVC animated:YES completion:nil];
}
}];
}