iOS實時監測網絡狀況

網絡連接與否,直接關係到獲取數據的方式,當沒網時,需要從本地獲取緩存數據,有wifi,展示高清圖片,無wifi時,只能展示縮略圖。因此,在展示數據時,首要做的就是判斷網絡,判斷網絡蘋果提供了這個Reachability類,需要自己添加到工程裏。另外需要添加庫SystemConfiguration.framework這個庫

蘋果提供的Reachability類的下載地址

https://developer.apple.com/library/ios/samplecode/Reachability/Reachability.zip

下面是代碼的實現

AppDelegate.h文件

 

#import <UIKit/UIKit.h>

#import "Reachability.h"

 

@interface AppDelegate : UIResponder <UIApplicationDelegate>

 

@property (strong, nonatomic) UIWindow *window;

//判斷網絡

@property(nonatomic,strong)Reachability*hostReach;

//記錄網絡狀態

@property(nonatomic,strong)NSString*isReachable;

 

@end

 

 

AppDelegate.m文件

 

 

#import "AppDelegate.h"

@interface AppDelegate ()

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    self.window = [[UIWindow alloc] init];

    self.window.frame = [UIScreen mainScreen].bounds;

    self.window.backgroundColor = [UIColor whiteColor];

    [self.window makeKeyAndVisible];

     //開啓網絡狀況的監聽

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];

    self.hostReach = [Reachability reachabilityWithHostName:@"www.baidu.com"] ;

    [self.hostReach startNotifier];  //開始監聽,會啓動一個run loop

    return YES;

}

//網絡鏈接改變時會調用的方法

-(void)reachabilityChanged:(NSNotification *)notification

{

    Reachability *currReach = [notification object];

    NSParameterAssert([currReach isKindOfClass:[Reachability class]]);

    //對連接改變做出響應處理動作

    NetworkStatus status = [currReach currentReachabilityStatus];

    //如果沒有連接到網絡就彈出提醒實況

    if(status == NotReachable)

    {

        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"網絡無連接" message:@"暫時無法訪問,請打開網絡" delegate:nil cancelButtonTitle:@"確定" otherButtonTitles:nil];

        [alert show];

        self.isReachable =@"NONet";

    }else if(status==ReachableViaWWAN){

    //非wifi狀態

        self.isReachable=@"YES+WWAN";

        

    }else{

        //wifi狀態

        self.isReachable =@"YES+WIFI";

    }

 }

 

在其他類裏面調用的時候加入如下代碼

可以在網絡連接狀態下再判斷wifi狀態,這裏我就省略了

   

 AppDelegate *appDlg = (AppDelegate *)[[UIApplication sharedApplication] delegate];

     if(![appDlg.isReachable isEqualToString:@"NONet"])

     {

     NSLog(@"網絡已連接");//執行網絡正常時的代碼 

     }

     else

     {

     NSLog(@"網絡連接異常");//執行網絡無連接時的代碼

     }

 

 

使用的時候請注意,self.hostReach 一定要初始化,要不然監聽的方法是不會走的,也無法進行監聽

 

 

發佈了30 篇原創文章 · 獲贊 7 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章