iOS检测网络状态

来源:互联网 发布:map源码 编辑:程序博客网 时间:2024/05/20 04:28

很多工程多需要用到网络,时刻需要对网络链接进行判断,下面介绍怎么使用网络链接第三方,进行判断网络以及判断是wifi,4G网络等等;

少说废话上代码:

#import "ViewController.h"#import "Reachability.h"@interface ViewController ()@property (nonatomic,strong) Reachability *netConnect;@end@implementation ViewController- (void)viewDidLoad {    [super viewDidLoad];            /***************  方法1 : block块  ***************/        /*     *1.最好是本公司的网站;     *2.国内能够访问的网站;     */        NSString *urlStr = @"写一个能连接的网址";        //创建监听络的对象self.netConnect    self.netConnect = [Reachability reachabilityWithHostname:urlStr];        __weak typeof(self) weakSelf = self;        //网络连接成功    self.netConnect.reachableBlock = ^(Reachability * reachability)    {             //打印网络名称,是 2G 网络还是 wifi ;        NSLog(@"connect success  :newName = %@",weakSelf.netConnect.currentReachabilityString);                //主线程        dispatch_async(dispatch_get_main_queue(), ^{            NSLog(@"reload data");        });    };        //网络连接失败    self.netConnect.unreachableBlock = ^(Reachability * reachability)    {                NSLog(@"connect error");                //主线程        dispatch_async(dispatch_get_main_queue(), ^{            NSLog(@"to do something");        });    };        //不要忘记启动噢    [self.netConnect startNotifier];            /***************  方法2 : 通知  ***************/    [[NSNotificationCenter defaultCenter] addObserver:self                                             selector:@selector(reachabilityChanged:)                                                 name:kReachabilityChangedNotification                                               object:self.netConnect];    }- (void)reachabilityChanged:(NSNotification *)notification{        /*     *currentReachabilityStatus     *     * NotReachable = 0,     * ReachableViaWiFi = 2,     * ReachableViaWWAN = 1     */        Reachability *reach = notification.object;        switch (reach.currentReachabilityStatus)    {        case NotReachable:            NSLog(@"connect error");            break;        case ReachableViaWiFi:            NSLog(@"connect wifi");            break;        case ReachableViaWWAN:            NSLog(@"connect wwan");            break;        default:            break;    }}


如果转载请注明转于:AirZilong的博客

3 0