從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); }