使用之前請從Apple網站下載樣本:點此下載
然後將Reachability.h 和 Reachability.m 加到自己的項目中,並引用 SystemConfiguration.framework,就可以使用了。
效果1:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{ self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease]; // Override point for customization after application launch. self.window.backgroundColor = [UIColor whiteColor]; //檢測網路情況 [self startNotificationNetwork]; [self.window makeKeyAndVisible]; return YES;}- (void)reachabilityChanged:(NSNotification *)notification{ Reachability *currentReach = [notification object]; NSParameterAssert([currentReach isKindOfClass:[Reachability class]]); NetworkStatus status = [currentReach currentReachabilityStatus]; NSString *netMsg = nil; switch (status) { case NotReachable: { netMsg = @"網路不可用"; break; } case ReachableViaWiFi: { netMsg = @"通過WiFi上網"; break; } case ReachableViaWWAN: { netMsg = @"通過3G/GPRS上網"; break; } } UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"連網提示" message:netMsg delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil]; [alert show]; [alert release];}-(void)startNotificationNetwork{ [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil]; Reachability * hostReach = [[Reachability reachabilityWithHostName:@"www.baidu.com"] retain]; [hostReach startNotifier];}
致謝:http://www.cnblogs.com/mrhgw/archive/2012/08/01/2617760.html
效果2:
//處理串連改變後的情況 //對串連改變做出響應的處理動作。- (void)updateInterfaceWithReachability: (Reachability*) curReach{ NetworkStatus status = [curReach currentReachabilityStatus]; if(status ==NotReachable) { UIAlertView*alertView = [[UIAlertView alloc]initWithTitle:@"溫馨提示" message:@"網路連接失敗,請檢查網路" delegate:nil cancelButtonTitle:@"確定" otherButtonTitles:nil]; [alertView show]; [alertView release]; }else{ NSLog(@"connect with the internet successfully"); } } //串連改變- (void)reachabilityChanged:(NSNotification* )note{ Reachability* curReach = [note object]; NSParameterAssert([curReach isKindOfClass: [Reachability class]]); [self updateInterfaceWithReachability: curReach];}-(void)startNotificationNetwork{ [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil]; Reachability * hostReach = [[Reachability reachabilityWithHostName:@"www.baidu.com"] retain]; [hostReach startNotifier];:}
致謝:http://blog.sina.com.cn/s/blog_91ff71c001016gql.html