Reputation: 16829
Assuming that I actually have an internet connection, I' use this code to know if the device is connected via WiFi or not :
+ (BOOL)hasWiFiConnection {
Reachability *reachability = [Reachability reachabilityForInternetConnection];
[reachability startNotifier];
NetworkStatus status = [reachability currentReachabilityStatus];
if (status == ReachableViaWiFi) {
return YES;
} else {
return NO;
}
}
Is that code fast to run?
I'm using it when generating URLs for pictures (so that I know if I load high or low resolution pictures). Those pictures are displayed in a list view (3 per line). When the I scroll the list the function is called several times per second. Is that efficient?
Upvotes: 0
Views: 188
Reputation: 994
if u dont want to use reachability Class use the following code.
@interface CMLNetworkManager : NSObject
+(CMLNetworkManager *) sharedInstance;
-(BOOL) hasConnectivity;
@end
Implementation
@implementation CMLNetworkManager
+(CMLNetworkManager *) sharedInstance {
static CMLNetworkManager *_instance = nil;
@synchronized(self) {
if(_instance == nil) {
_instance = [[super alloc] init];
}
}
return _instance;
}
-(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;
}
@end
use the bool method with class shared Instance were ever you want
Upvotes: 2