2015-04-17 87 views
0

我試圖檢測互聯網是否在使用AFNetworking的設備上工作或;請參閱SO AFNetworking 2.0 Reachability的答案。我能夠檢測到設備連接到WiFi或3G ..如何檢查互聯網是否工作在ios

問題是其實互聯網並不像WIFI一樣工作,但互聯網不工作。

如何檢測網絡是否工作。就像我們檢查使用ping ....

我使用檢查以下

-(BOOL)connected { 

    __block BOOL reachable; 

// Setting block doesn't means you area running it right now 
[[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) { 

    switch (status) { 
     case AFNetworkReachabilityStatusNotReachable: 
      NSLog(@"No Internet Connection"); 
      reachable = NO; 
      break; 
     case AFNetworkReachabilityStatusReachableViaWiFi: 
      NSLog(@"WIFI"); 

      reachable = YES; 
      break; 
     case AFNetworkReachabilityStatusReachableViaWWAN: 
      NSLog(@"3G"); 
      reachable = YES; 
      break; 
     default: 
      NSLog(@"Unkown network status"); 
      reachable = NO; 
      break; 

    } 
}]; 
// and now activate monitoring 
[[AFNetworkReachabilityManager sharedManager] startMonitoring]; 

return reachable; 

}

+1

這裏呼籲通知功能。 –

+0

在我的情況下沒有登錄需要,但即使登錄需要我需要檢查是我能夠ping從設備說,當AFNetworkReachabilityStatusReachableViaWiFi發現是真的 – hii

+0

您可以檢查相同的問題:http:// stackoverflow .COM /問題/ 15146607 /檢測,互聯網連接狀態 - 不只是-WiFi的IOS –

回答

0

您可以使用可達性,以確定是否你有一個連接到網絡的功能。但是,如果您確實需要確定您有一個可行的互聯網連接,那麼最好的方法是嘗試建立一個實際的連接並檢查結果。爲此使用NSURLConnection。

NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.apple.com/"] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0]; 
NSMutableData *receivedData = [NSMutableData dataWithCapacity:0]; 
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self]; 

if(!theConnection) { // Something went wrong. 
    receivedData = nil; 
} 

要確定是否建立一個可行的連接,檢查使用的委託方法連接的結果:

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error 
{ 
    NSLog(@"Connection failed! Error - %@ %@", [error localizedDescription], 
     [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]); 
} 
1

添加通知觀察員對網絡狀態的變化。 就像在應用程序委託類中添加以下代碼下完成發射類

[[AFNetworkReachabilityManager sharedManager] startMonitoring]; 
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveNetworkChnageNotification:) name:AFNetworkingReachabilityDidChangeNotification object:nil]; 

加入全球alertview在.h文件中。因爲它會在網絡狀態變化時出現和消失。如果需要登錄電子防火牆妳比在設備的情況下訪問斜面互聯網連接到WiFi或3G

- (void)receiveNetworkChnageNotification:(NSNotification *)notification 
{ 
    if (![self isReachable]) 
    { 
     self.alertView = [[UIAlertView alloc] initWithTitle:@"No Internet Connection" message:@"You have no internet connection on your device, please check and try again later." delegate:nil cancelButtonTitle:@"Cancel" otherButtonTitles:nil]; 
     [self.alertView show]; 
    } 
    else 
    { 
     [self.alertView dismissWithClickedButtonIndex:0 animated:YES]; 
    } 
}