iOS检测网络状态

很多工程多需要用到网络,时刻需要对网络链接进行判断,下面介绍怎么使用网络链接第三方,进行判断网络以及判断是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
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值