美文网首页
Reachability 使用

Reachability 使用

作者: foolish_hungry | 来源:发表于2018-04-30 18:21 被阅读0次

    直接上代码 (希望大家能提出建议)

    // .h 文件
    #import <Foundation/Foundation.h>
    typedef NS_ENUM(NSInteger, NetWorkStatusType) {
        network_status_wifi,    // wifi
        network_status_wwan,    // 蜂窝移动网络
        network_status_none     // 无网络
    };
    
    typedef void(^netWorkBlock)(NetWorkStatusType type);
    
    @interface SXReachbilityHelper : NSObject
    // 是否有网络
    + (BOOL)isReachbility;
    // 获取网络类型
    + (void)reachbilityStatus:(netWorkBlock)completion;
    // 网络状态监听
    + (void)starNetWorkStatsuNotifactionWithTarget:(id)target;
    
    @end
    
    // .m文件
    #import "SXReachbilityHelper.h"
    #import <Reachability/Reachability.h>
    
    @implementation SXReachbilityHelper
    
    + (BOOL)isReachbility {
        Reachability *reachability = [Reachability reachabilityForInternetConnection];
        BOOL flag = YES;
        switch (reachability.currentReachabilityStatus) {
            case NotReachable:
                flag = NO;
                break;
            case ReachableViaWiFi:
                flag = YES;
                break;
            case ReachableViaWWAN:
                flag = YES;
                break;
        }
        return flag;
    }
    
    + (void)reachbilityStatus:(netWorkBlock)completion {
        Reachability *reachability = [Reachability reachabilityForInternetConnection];
        switch (reachability.currentReachabilityStatus) {
            case NotReachable:
                completion(network_status_none);
                break;
            case ReachableViaWiFi:
                completion(network_status_wifi);
                break;
            case ReachableViaWWAN:
                completion(network_status_wwan);
                break;
        }
    }
    
    // 网络状态监听    target 可以指定 任意对象    方法的实现在相应对象
    + (void)starNetWorkStatsuNotifactionWithTarget:(id)target {
        // Allocate a reachability object
        Reachability* reach = [Reachability reachabilityWithHostname:@"www.google.com"];
        
        // Tell the reachability that we DON'T want to be reachable on 3G/EDGE/CDMA
        reach.reachableOnWWAN = NO;
        
        // Here we set up a NSNotification observer. The Reachability that caused the notification
        // is passed in the object parameter
        [[NSNotificationCenter defaultCenter] addObserver:target
                                                 selector:@selector(reachabilityChanged:)
                                                     name:kReachabilityChangedNotification
                                                   object:nil];
        
        [reach startNotifier];
    }
    
    
    @end
    
    

    相关文章

      网友评论

          本文标题:Reachability 使用

          本文链接:https://www.haomeiwen.com/subject/xxctrftx.html