如何检查互联网连接在iOS?

我如何检查应用程序是否连接到互联网? 目前,我在我的appdelegate.m文件中使用这个代码

 dispatch_queue_t connectivityThread = dispatch_queue_create("com.gm.kart.connectivity", NULL); dispatch_async(connectivityThread, ^{ while (true){ if([GMMConnectivity hasConnectivity]) NSLog(@"%@", @"connected"); else NSLog(@"Not connected"); usleep(10000000); } }); 

当我点击我的loginbutton,我想检查互联网是否连接或不使用NSnotificationcenter

请帮帮我

下载后的例子。

http://developer.apple.com/iphone/library/samplecode/Reachability/index.html

你可以在你的项目中使用它像波纹pipe的步骤:

included Apple's Reachability.h & .m from their Reachability example.

add the SystemConfiguration framework.

把bellow方法放到你的appdelegare.m文件中:

 - (BOOL) connectedToNetwork{ Reachability* reachability = [Reachability reachabilityWithHostName:@"google.com"]; NetworkStatus remoteHostStatus = [reachability currentReachabilityStatus]; if(remoteHostStatus == NotReachable) { isInternet =NO; } else if (remoteHostStatus == ReachableViaWWAN) { isInternet = TRUE; } else if (remoteHostStatus == ReachableViaWiFi) { isInternet = TRUE; } return isInternet; } 

isInternet是一个BOOL在你的.h类中声明的

根据你的代码:

 dispatch_queue_t connectivityThread = dispatch_queue_create("com.GMM.assamkart.connectivity", NULL); dispatch_async(connectivityThread, ^{ while (true){ isInternet =[self connectedToNetwork]; if (isInternet) { NSLog(@"connected"); } else { NSLog(@"Not connected"); } // usleep(10000000); } }); 
 -(BOOL) connectedToInternet { NSString *URLString = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://www.google.com"]]; return ( URLString != NULL ) ? YES : NO; }