網絡狀態檢測Reachability

jopen 9年前發布 | 741 次閱讀 Objective-C IOS

#import "Reachability.h"

@interface JRViewController ()<UIActionSheetDelegate> @property(nonatomic,strong) Reachability * reach; @end

@implementation JRViewController

  • (void)viewDidLoad { [super viewDidLoad];

//監聽Reachability.h————————————————————————————————————————————————————————————————

//
[self monitorNetState:nil];

// 開啟通知監控,實時等待
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(monitorNetState:) name:kReachabilityChangedNotification object:nil];//object是指監聽誰發出的通知,在這里可以寫self.reach,也可以寫nil
[self.reach startNotifier];//一定要寫開始監控

}

//** //reachability監聽————————————————————————————————————————————————————————————————

  • (void) monitorNetState:(NSNotification *)noti { NSLog(@"%@", noti); if(self.reach==nil)// {
      self.reach=[Reachability reachabilityForInternetConnection];//不是單例
    //他還有兩個子類

// ReachableViaWiFi; // ReachableViaWWAN;

}

if(self.reach.currentReachabilityStatus!=NotReachable)
{

    if (self.reach.currentReachabilityStatus==ReachableViaWiFi)
    {
        NSLog(@"wifi");
    }
    else
    {
        NSLog(@"3g/2g");
    }
}
else
{
    NSLog(@"沒有網");
}

}

//移除監聽 -(void)dealloc{ //reachability需要自己停止 [self.reach stopNotifier];

[[NSNotificationCenter defaultCenter] removeObserver:self];

}

@end </pre>

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!