說明:本人是使用AFNetworking進行網絡判斷的.網絡
實現發送網絡請求以前判斷網絡狀態的步驟app
// 定義判斷網絡狀態的全局變量 BOOL whetherHaveNetwork;
@interface AppDelegate () /** 網絡狀態檢查者 */ @property(nonatomic, strong) AFNetworkReachabilityManager *networkMonitorManager; @end @implementation AppDelegate #pragma mark - 懶加載 - (AFNetworkReachabilityManager *)networkMonitorManager { if (!_networkMonitorManager) { _networkMonitorManager = [AFNetworkReachabilityManager sharedManager]; [_networkMonitorManager startMonitoring]; //開始監聽 } return _networkMonitorManager; } - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // 1.建立窗口 self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds]; // 2.設置根控制器 FKTabBarController *tabBarController = [[FKTabBarController alloc] init]; self.window.rootViewController = tabBarController; // 3.設置窗口爲UIApplication的主窗口,而且顯示出來 [self.window makeKeyAndVisible]; // 開啓網絡監聽 [self.networkMonitorManager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) { if (status == AFNetworkReachabilityStatusNotReachable) {// 沒有網絡 whetherHaveNetwork = NO; NSLog(@"沒有網絡:ifHaveNetwork = %d", whetherHaveNetwork); }else{// 有網絡 whetherHaveNetwork = YES; NSLog(@"有網絡:ifHaveNetwork = %d", whetherHaveNetwork); } }]; return YES; } }
// 判斷當前網絡的全局變量 // 建議吧這行代碼放在pch文件中,這樣你就不須要每一個文件都寫一次這行代碼 extern BOOL whetherHaveNetwork;
if (whetherHaveNetwork) { // 在這裏發送網絡請求 }
文/IMKel(簡書做者)
原文連接:http://www.jianshu.com/p/e610bd728a53atom