运行应用时先进行网络判断,判断目前处于什么网络下,判断步骤如下:
1.下载AFNetworking
2.导入头文件 #import "AFNetworkReachabilityManager.h"
3.实现代码
// 1.获得网络监控的管理者
AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
// 2.设置网络状态改变后的处理
[manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
// 当网络状态改变了, 就会调用这个block
switch (status) {
case AFNetworkReachabilityStatusUnknown: // 未知网络
{
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"当前为未知网络" preferredStyle:UIAlertControllerStyleAlert];
/* 创建action对象 */
UIAlertAction *actionConfirm = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
}];
/* alert添加action对象 */
[alert addAction:actionConfirm];
[self presentViewController:alert animated:YES completion:^{
}];
break;
}
case AFNetworkReachabilityStatusNotReachable: // 没有网络(断网)
{
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"亲!无网络!请查看网络设置" preferredStyle:UIAlertControllerStyleAlert];
/* 创建action对象 */
UIAlertAction *actionConfirm = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
}];
/* alert添加action对象 */
[alert addAction:actionConfirm];
[self presentViewController:alert animated:YES completion:^{
}];
break;
}
case AFNetworkReachabilityStatusReachableViaWWAN: // 手机自带网络
{
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:@"亲!正在使用手机3G/4G网" preferredStyle:UIAlertControllerStyleAlert];
/* 创建action对象 */
UIAlertAction *actionConfirm = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
}];
/* alert添加action对象 */
[alert addAction:actionConfirm];
[self presentViewController:alert animated:YES completion:^{
}];
break;
}
case AFNetworkReachabilityStatusReachableViaWiFi: // WIFI
{
NSLog(@"WIFI");
UIAlertView *alertView2 = [[UIAlertView alloc] initWithTitle:@"提示" message:@"亲!正在使用wifi" delegate:self cancelButtonTitle:@"确认" otherButtonTitles:nil, nil];
[alertView2 show];
break;
}
}
}];
// 3.开始监控
[manager startMonitoring];