1. 程式人生 > >ios之好用的Reachability

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中呼叫即可 全域性可以監聽