檢測網路狀態

weixin_34054866發表於2016-01-03

只要網路狀態發生了變化,在任何一個檢視控制器都會給出相應的提示

說明: 這裡需要匯入第三方庫,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;
}

相關文章