iOS中单点的Internet连接方法?
我在我的应用程序中有这个方法来检查互联网iOS中单点的Internet连接方法?,ios,iphone,objective-c,Ios,Iphone,Objective C,我在我的应用程序中有这个方法来检查互联网 /* Connectivity testing code pulled from Apple's Reachability Example: http://developer.apple.com/library/ios/#samplecode/Reachability */ -(BOOL)hasConnectivity { struct sockaddr_in zeroAddress; bzero(&zeroAddress,
/*
Connectivity testing code pulled from Apple's Reachability Example: http://developer.apple.com/library/ios/#samplecode/Reachability
*/
-(BOOL)hasConnectivity {
struct sockaddr_in zeroAddress;
bzero(&zeroAddress, sizeof(zeroAddress));
zeroAddress.sin_len = sizeof(zeroAddress);
zeroAddress.sin_family = AF_INET;
SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, (const struct sockaddr*)&zeroAddress);
if(reachability != NULL) {
//NetworkStatus retVal = NotReachable;
SCNetworkReachabilityFlags flags;
if (SCNetworkReachabilityGetFlags(reachability, &flags)) {
if ((flags & kSCNetworkReachabilityFlagsReachable) == 0)
{
// if target host is not reachable
return NO;
}
if ((flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0)
{
// if target host is reachable and no connection is required
// then we'll assume (for now) that your on Wi-Fi
return YES;
}
if ((((flags & kSCNetworkReachabilityFlagsConnectionOnDemand ) != 0) ||
(flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0))
{
// ... and the connection is on-demand (or on-traffic) if the
// calling application is using the CFSocketStream or higher APIs
if ((flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0)
{
// ... and no [user] intervention is needed
return YES;
}
}
if ((flags & kSCNetworkReachabilityFlagsIsWWAN) == kSCNetworkReachabilityFlagsIsWWAN)
{
// ... but WWAN connections are OK if the calling application
// is using the CFNetwork (CFSocketStream?) APIs.
return YES;
}
}
}
return NO;
}
我必须在每节课上粘贴这个方法,并像这样检查互联网
if([self hasConnectivity] == YES){
我想把这个方法放在一个类中,就像我把宏放在Constants.h或.pch文件中一样
是否有任何方法(除了委托,因为我不想太多地使用委托)来做到这一点
感谢将
-(BOOL)hasConnectivity
更改为+(BOOL)hasConnectivity
(这将实例方法转换为类方法)。将其添加到名为可达性的类中。将Reachability.h
添加到you.pch。现在调用[Reachability hasConnectivity]
并从应用程序中的任何位置检查其返回值。轰 您可以将该方法添加为NSObject的类别,这样它将可用于所有类。
因此,您可以为NSObject创建一个名为Network的类别,例如:
//NSObject+Network.h
@interface NSObject (Network)
-(BOOL)hasConnectivity;
@end
// NSObject+Network.m
@implementation NSObject (Network)
-(BOOL)hasConnectivity {
...
}
@end
在.pch中导入NSObject+Network.h,在所有类中,boom,您都可以访问hasConnectivity。是的,您可以将
可达性.h
添加到常量.h
中,只要您在要调用[可达性hasConnectivity]
的类中导入常量.h
。