代码改变世界

转:iPhone 网络连接检测(Wifi,3G,Edge)代码之一

2011-11-26 11:12  张智清  阅读(533)  评论(0编辑  收藏  举报

这个类可以用来检测用户是否连接到internet,只有一个方法,返回YES或NO。功能类似Reachability。

类的头文件Connection.h

//
// Connection.h
//
#import <Foundation/Foundation.h>
#import <SystemConfiguration/SystemConfiguration.h>
#import <netinet/in.h>
#import <arpa/inet.h>
#import <netdb.h>

@interface Connection : NSObject {
}
+ (BOOL) isConnected;
@end

类的实现文件Connection.m

//
// Connection.m
//
@implementation Connection

+ (BOOL) isConnected {
// Create zero addy
struct sockaddr_in zeroAddress;
bzero(&zeroAddress, sizeof(zeroAddress));
zeroAddress.sin_len = sizeof(zeroAddress);
zeroAddress.sin_family = AF_INET;

// Recover reachability flags
SCNetworkReachabilityRef defaultRouteReachability = SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&zeroAddress);
SCNetworkReachabilityFlags flags;
BOOL didRetrieveFlags = SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags);
CFRelease(defaultRouteReachability);
if(!didRetrieveFlags) {
NSLog(@"Error,Could not recover network reachability flags");
return NO;
}
BOOL isReachable = flags & kSCNetworkFlagsReachable;
BOOL needsConnection = flags & kSCNetworkFlagsConnectionRequired;
BOOL nonWiFi = flags & kSCNetworkReachabilityFlagsTransientConnection;

NSURL *testURL = [NSURL URLWithString:@"http://www.google.com/"];
NSURLRequest *testRequest = [NSURLRequest requestWithURL:testURL cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:20.0];
NSURLConnection *testConnection = [[NSURLConnection alloc] initWithRequest:testRequest delegate:self] autorelease];
return ((isReachable && !needsConnection) || nonWiFi) ? (testConnection ? YES : NO) : NO;
}

@end

最后别忘了添加必要的frameworks : SystemConfiguration and libz.1.1.3.dylib

示例代码:

if ([Connection isConnected]) {......}
else {......}