//在程序的啓動處,開啓通知
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
//.....
//開啓網絡狀況的監聽
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(reachabilityChanged:)
name: kReachabilityChangedNotification
object: nil];
hostReach = [[Reachability reachabilityWithHostName:@"www.google.com"] retain];//可以以多種形式初始化
[hostReach startNotifier]; //開始監聽,會啓動一個run loop
[self updateInterfaceWithReachability: hostReach];
//.....
}
// 連接改變
- (void) reachabilityChanged: (NSNotification* )note
{
Reachability* curReach = [note object];
NSParameterAssert([curReach isKindOfClass: [Reachability class]]);
[self updateInterfaceWithReachability: curReach];
}
//處理連接改變後的情況
- (void) updateInterfaceWithReachability: (Reachability*) curReach
{
//對連接改變做出響應的處理動作。
NetworkStatus status = [curReach currentReachabilityStatus];
if (status == NotReachable) { //沒有連接到網絡就彈出提實況
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"My App Name"
message:@"NotReachable"
delegate:nil
cancelButtonTitle:@"YES" otherButtonTitles:nil];
[alert show];
[alert release];
}
}