iOS網路狀態檢測

來源:互聯網
上載者:User

從Git庫下載

https://github.com/tonymillion/Reachability

把兩個檔案Reachability.h 和 Reachability.m檔案添加到工程中。

添加架構支援SystemConfiguration.framework

添加標頭檔聲明:

@class Reachability;@interface AppDelegate : UIResponder <UIApplicationDelegate>{    UINavigationController *_navigationController;    Reachability  *hostReach;}@property (strong, nonatomic) UIWindow *window;@property (strong, nonatomic) UIViewController *viewController;@property (strong, nonatomic) UINavigationController *navigationController;@end

AppDelegate.m實現檔案中

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 方法中加入如下代碼

 [self netWorkChecker];

添加網路檢測代碼

#pragma mark network check-(void)netWorkChecker{    hostReach = [Reachability reachabilityWithHostname:@"www.apple.com"];    switch ([hostReach currentReachabilityStatus]) {        case NotReachable:            NSLog(@"沒有網路連接");            // 沒有網路連接            break;        case ReachableViaWWAN:            // 使用3G網路            NSLog(@"使用3G網路");            break;        case ReachableViaWiFi:            // 使用WiFi網路            NSLog(@"使用WiFi網路");            break;    }    //   }

添加網路變化的通知

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 方法中加入如下代碼

 [self addNetWorkChangeNotification];

-(void)addNetWorkChangeNotification{    [[NSNotificationCenter defaultCenter] addObserver:self                                             selector:@selector(reachabilityChanged:)                                                 name: kReachabilityChangedNotification                                               object: nil];    hostReach = [Reachability reachabilityWithHostname:@"www.google.com"]  ;    [hostReach startNotifier];}- (void)reachabilityChanged:(NSNotification *)note{    Reachability* curReach = [note object];    NSParameterAssert([curReach isKindOfClass: [Reachability class]]);    NetworkStatus status = [curReach currentReachabilityStatus];    NSLog(@"reachabilityChanged delegate NotReachable : %d ", status);     }

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.