2017-03-13 33 views
0

如何檢查網絡連接可用如何檢查可用的互聯網的WiFi

我使用蘋果可達類來檢查網絡狀態通過使用下面的代碼

-(BOOL)isInternetConnectionAvailable{ 

    return ([[Reachability reachabilityForInternetConnection]currentReachabilityStatus] == NotReachable)?NO:YES; 
} 

我我有熱點的移動然後連接到我的iPhone與WiFi。 然後移動數據關閉,熱點打開。 但rechability類正在返回ReachableViaWiFi 如何檢查網絡是否有互聯網。

+0

找到答案:http://stackoverflow.com/questions/1083701/how-to-check-for-an-active-internet-connection-on-ios-or-osx?page=1&tab=最老的#tab-top] –

回答

0

爲此,您已經檢查互聯網,因爲這使互聯網驗證類,然後每個地方,你使用互聯網打電話給那個類。

在.h文件中創建一個靜態方法,如下所示。

#import <Foundation/Foundation.h> 

@interface InternetValidation : NSObject { 

} 

+ (BOOL) connectedToNetwork; 

@end 

然後,在你的.m文件

#import "InternetValidation.h" 
#import <SystemConfiguration/SCNetworkReachability.h> 
#include <netinet/in.h> 

@implementation InternetValidation 

+ (BOOL) connectedToNetwork 
{ 


    BOOL success = NO; 
    const char *host_name = [@"google.com" 
          cStringUsingEncoding:NSASCIIStringEncoding]; 

    SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithName(NULL, 
                       host_name); 
    SCNetworkReachabilityFlags flags; 
    success = SCNetworkReachabilityGetFlags(reachability, &flags); 
    BOOL isAvailable = success && (flags & kSCNetworkFlagsReachable) && !(flags & kSCNetworkFlagsConnectionRequired); 
    if (isAvailable) { 
     success = YES; 
    }else{ 
     success = NO; 
    } 
    //NSLog(@"%d",success); 
    return success; 

} 


@end 

現在,導入這個類,你要檢查網絡連接。

然後以這種方式調用Internet Class Method。

if ([InternetValidation connectedToNetwork]){ 
    //Do your code here. 
} 
else{ 
    // No Internet; 
} 
+1

這不起作用。它返回是,即使互聯網不可用。 –