我正在iPhone中开发应用程序,它是从网站动态获取数据,我正在检查Wifi和GPRS是否已连接但是当无法访问wifi时,应用程序崩溃。
我正在使用此方法检查连接。
+ (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"];
}
由于 瓦代夫卢
答案 0 :(得分:4)
为什么要乱用IP地址?您可以直接致电SCNetworkReachabilityCreateWithName()
:
SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, "google.com");
答案 1 :(得分:2)
GitHub上还有一个开源NPReachability类,它执行相同的操作,但使用块作为处理程序。
答案 2 :(得分:-1)
您可以使用隐藏的UIWebView并加载网站。然后使用UIWebView.h中的方法检测加载是否成功。