检测网络状态

只要网络状态发生了变化,在任何一个视图控制器都会给出相应的提示

说明: 这里需要导入第三方库,1. MBProgressHUD 2. AFNetworking
导入头文件 MBProgressHUD.h, AFNetworking.h

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // 应用程序加载完成

    UIWindow *window = ((AppDelegate *) [UIApplication sharedApplication].delegate).window;
    
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        // 使用MBProgressHUD三方库创建弹框,给出相应的提示
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:window animated:YES];
        hud.mode = MBProgressHUDModeText;
        switch (status) {
            case AFNetworkReachabilityStatusNotReachable:
                // 弹框提示的内容
                hud.labelText = @"世界上最遥远的距离就是没网";
                break;
            case AFNetworkReachabilityStatusReachableViaWWAN:
                hud.labelText = @"2G/3G/4G";
                break;
            case AFNetworkReachabilityStatusReachableViaWiFi:
                hud.labelText = @"WiFi在线";
            default:
                break;
        }
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            // 显示时间2s
            sleep(2);
            dispatch_async(dispatch_get_main_queue(), ^{
                // 让弹框消失
                [MBProgressHUD hideHUDForView:window animated:YES];
            });
        });
    }];
    [manager startMonitoring];
    
    return YES;
}

你可能感兴趣的:(检测网络状态)