爲此,您已經檢查互聯網,因爲這使互聯網驗證類,然後每個地方,你使用互聯網打電話給那個類。
在.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;
}
找到答案:http://stackoverflow.com/questions/1083701/how-to-check-for-an-active-internet-connection-on-ios-or-osx?page=1&tab=最老的#tab-top] –