Reputation: 508
I am developing app in iPhone which is fetch the data from website dynamically, I am checking whether Wifi and GPRS are connected but when wifi is not reachable, App crash.
I am using this method to check connection.
+ (BOOL) isConnected {
// Part 1 - Create Internet socket addr of zero
struct sockaddr_in zeroAddr;
bzero(&zeroAddr, sizeof(zeroAddr));
zeroAddr.sin_len = sizeof(zeroAddr);
zeroAddr.sin_family = AF_INET;
// Part 2- Create target in format need by SCNetwork
SCNetworkReachabilityRef target =
SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *) &zeroAddr);
// Part 3 - Get the flags
SCNetworkReachabilityFlags flags;
SCNetworkReachabilityGetFlags(target, &flags);
// Part 4 - Create output
NSString *sNetworkReachable;
if (flags & kSCNetworkFlagsReachable)
sNetworkReachable = @"YES";
else
sNetworkReachable = @"NO";
NSString *sCellNetwork;
if (flags & kSCNetworkReachabilityFlagsIsWWAN)
sCellNetwork = @"YES";
else
sCellNetwork = @"NO";
// Get host entry info for given host
struct hostent *remoteHostEnt = gethostbyname("google.com");
if(remoteHostEnt == nil ) return NO;
// Get address info from host entry
struct in_addr *remoteInAddr = (struct in_addr *) remoteHostEnt->h_addr_list[0];
// Convert numeric addr to ASCII string
char *sRemoteInAddr = inet_ntoa(*remoteInAddr);
NSString *s = [[NSString alloc]
initWithFormat:
@"Network Reachable: %@\n"
@"Cell Network: %@\n"
@"Remote IP: %s\n",
sNetworkReachable,
sCellNetwork,
sRemoteInAddr];
// Add text
[sCellNetwork release];
[sNetworkReachable release];
NSLog(@"Message:%@",s);
return [sNetworkReachable isEqualToString:@"YES"];
}
Thanks Vadivelu
Upvotes: 1
Views: 5645
Reputation: 150745
Search for the Reachability sample application on developer.apple.com
There is also the Open Source NPReachability class on GitHub which does the same thing but uses a block as a handler.
Upvotes: 2
Reputation: 2489
You could use a hidden UIWebView and load a website to it. Then use methods from the UIWebView.h to detect, whether loading was successful or not.
Upvotes: -1
Reputation: 23722
Why mess with IP addresses? You can call SCNetworkReachabilityCreateWithName()
directly instead:
SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, "google.com");
Upvotes: 4