我正在開發iPhone應用程序,它是從網站動態獲取數據,我正在檢查Wifi和GPRS是否連接,但是當WiFi無法連接時,應用程序崩潰。檢查網絡連接iPhone
我正在使用此方法來檢查連接。
+ (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"];
}
感謝 瓦代夫盧
沒有理由這樣做。 Apple已經提供了一個用於檢查網絡可達性的API。 – 2012-04-02 11:11:34