ios之好用的Reachability

#import <Foundation/Foundation.h>

 

@interface NetWorkTool : NSObject

+ (instancetype)shareInstance;

- (void)startListing;

@end

 

 

#import "NetWorkTool.h"

@import Reachability;

@interface NetWorkTool()

@property (nonatomic) Reachability *hostReachability;

@property (nonatomic) Reachability *internetReachability;

@end

@implementation NetWorkTool

static NetWorkTool *tool = nil;

+(instancetype)shareInstance

{

    static dispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{

        tool = [[NetWorkTool alloc]init];

    });

    return tool;

}

 

- (void)startListing

{

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

    

    NSString *remoteHostName = @"www.apple.com";

    

    self.hostReachability = [Reachability reachabilityWithHostName:remoteHostName];

    [self.hostReachability startNotifier];

    [self updateInterfaceWithReachability:self.hostReachability];

    

    self.internetReachability = [Reachability reachabilityForInternetConnection];

    [self.internetReachability startNotifier];

    [self updateInterfaceWithReachability:self.internetReachability];

 

}

- (void) reachabilityChanged:(NSNotification *)note

{

    Reachability* curReach = [note object];

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

    [self updateInterfaceWithReachability:curReach];

}

 

- (void)updateInterfaceWithReachability:(Reachability *)reachability

{

 

    if (reachability == self.internetReachability)

    {

        [self configureReachability:reachability];

    }

    

}

 

- (void)configureReachability:(Reachability *)reachability

{

    NetworkStatus netStatus = [reachability currentReachabilityStatus];

    BOOL connectionRequired = [reachability connectionRequired];

    

    switch (netStatus)

    {

        case NotReachable:        {

            NSLog(@"没有网络");

            connectionRequired = NO;

            break;

        }

            

        case ReachableViaWWAN:        {

            NSLog(@"手机自带网络");

            break;

        }

        case ReachableViaWiFi:        {

            NSLog(@"wifi网络");

            break;

        }

    }

 

}

 

 

- (void)dealloc

{

    [[NSNotificationCenter defaultCenter] removeObserver:self name:kReachabilityChangedNotification object:nil];

}

@end

 

#define NetWorkManager   [NetWorkTool shareInstance]

 [NetWorkManager startListing];

 

didFinishLaunchingWithOptions中调用即可 全局可以监听

 

posted on 2018-10-31 11:04  Truce_Lee  阅读(296)  评论(0编辑  收藏  举报