iOS Reachability監(jiān)控網(wǎng)絡(luò)使用

//聯(lián)系人:石虎QQ: 1224614774昵稱:嗡嘛呢叭咪哄

第一步:在AppDelegate.h添加頭文件"Reachability.h"

第二步:導(dǎo)入框架SystemConfiguration.frame

第三步:下面是代碼:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

{

//開啟網(wǎng)絡(luò)狀況的監(jiān)聽

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];

self.hostReach = [Reachability reachabilityWithHostName:@"www.baidu.com"] ;

//開始監(jiān)聽,會啟動(dòng)一個(gè)run loop

[self.hostReach startNotifier];

}

-(void)reachabilityChanged:(NSNotification *)note

{

Reachability *currReach = [note object];

NSParameterAssert([currReach isKindOfClass:[Reachability class]]);

//對連接改變做出響應(yīng)處理動(dòng)作

NetworkStatus status = [currReach currentReachabilityStatus];

//如果沒有連接到網(wǎng)絡(luò)就彈出提醒實(shí)況

self.isReachable = YES;

if(status == NotReachable)

{

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"網(wǎng)絡(luò)連接異常" message:nil delegate:nil cancelButtonTitle:@"確定" otherButtonTitles:nil];

[alert show];

[alert release];

self.isReachable = NO;

return;

}

if (status==kReachableViaWiFi||status==kReachableViaWWAN) {

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"網(wǎng)絡(luò)連接信息" message:@"網(wǎng)絡(luò)連接正常" delegate:nil cancelButtonTitle:@"確定" otherButtonTitles:nil];

//? ? ? ? [alert show];

[alert release];

self.isReachable = YES;

}

}

然后在每個(gè)頁面的viewWillAppear:加上:

-(void)viewWillAppear:(BOOL)animated

{

[super viewWillAppear:YES];

AppDelegate *appDlg = (AppDelegate *)[[UIApplication sharedApplication] delegate];

if(appDlg.isReachable)

{

NSLog(@"網(wǎng)絡(luò)已連接");//執(zhí)行網(wǎng)絡(luò)正常時(shí)的代碼

}

else

{

NSLog(@"網(wǎng)絡(luò)連接異常");//執(zhí)行網(wǎng)絡(luò)異常時(shí)的代碼

UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"網(wǎng)絡(luò)連接異常" message:nil delegate:nil cancelButtonTitle:@"確定" otherButtonTitles:nil];

[alert show];

[alert release];

}

}這樣就可以檢查到在運(yùn)行程序時(shí)網(wǎng)絡(luò)突然的中斷和連接。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容