2013-04-17 77 views
0

如何檢查應用程序是否連接到互聯網? 目前,我在我的appdelegate.m文件如何檢查ios中的互聯網連接?

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

使用此代碼,當我點擊我的登錄按鈕,我想要做一個上網一查是否連接不使用NSnotificationcenter

請幫我

+0

你搜索某些內容? http://www.google.com/#output=search&sclient=psy-ab&q=How+to+check+internet+connectivity+in+ios%3F&oq=How+to+check+internet+connectivity+in+ios%3F&gs_l = hp.3..0i22i30l2.950.950.0.1947.1.1.0.0.0.0.173.173.0j1.1.0 ... 0.0 ... 1c.1.9.psy-ab.FQR8PLKiNzs&PBX = 1&BAV = on.2,or.r_qf。 &bvm = bv.45368065,d.bmk&fp = 55f9ca2dd31d2c85&biw = 1600&bih = 799 – Buntylm

+0

tried..but與我的代碼沒有任何關係 – Naveen

+0

我不知道GMMConnectivity,但這裏是您如何使用Reachability(Apple提供的類)和NSNotificationCenter :http://stackoverflow.com/a/15854823/412916 – Jano

回答

11

下載以後下面的例子。

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

,你可以在你的項目中使用它像波紋管的步驟: -

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

add the SystemConfiguration framework.

把波紋管的方法到您的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 declear到您的.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); 
    } 
}); 
+0

no @nitin Gohel能否建議一種方法來解決我的代碼 – Naveen

-1
-(BOOL) connectedToInternet 

{ 
    NSString *URLString = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"http://www.google.com"]]; 

return (URLString != NULL) ? YES : NO; 

} 
+1

這段代碼是同步的,所以它會中斷你的主線程。每次您想要檢查互聯網連接時,您還必須下載該網頁。絕對使用可達性代替。 – OlivaresF