在查看此post后,我编写了以下例程,以编程方式确定蜂窝和WiFi数据的连接状态。
我编写的例程效果很好,但与设备屏幕顶部的WiFi和蜂窝连接图标显示的状态相比,它返回的信息延迟了大约20到40秒。
以下是代码:
- (PSTR) isLinkedToTypeCom: (PSTR) reqTypCom andTypeFam: (int) reqTypFam
//...reqTypCom = "pdp_ip0" or "en0" aka (cell or WiFi)
// reqTypFam = AF_INET or AF_INET6 aka ("IPv4" or IPv6")
//
//...derived from from Stack Overflow:
// https://stackoverflow.com/questions/31721696/ios-check-if-cellular-technology-available-even-if-the-device-is-on-wifi
//...returns an ip address string if both the reqTypCom and the reqTypFam are
// matched and the entry is active. otherwise, it will return NULLSTR.
{
struct ifaddrs * pAddrs;
struct ifaddrs * pAddr;
NSString ipAdr = NULLSTR;
if ( getifaddrs( &pAddrs ) == 0 )
{
pAddr = pAddrs;
while( pAddr != NULL )
{
NSString * curTypCom = [NSString stringWithUTF8String: pAddr->ifa_name ];
if ( [curTypCom isEqualToString: reqTypCom] )
{
sa_family_t curTypFam = pAddr->ifa_addr->sa_family;
bool isActive = pAddr->ifa_flags & IFF_UP;
if ( curTypFam == reqTypFam && isActive == true )
{
if ( reqTypFam == AF_INET )
{
ipAdr = [NSString stringWithUTF8String:
inet_ntoa(((struct sockaddr_in *)pAddr->ifa_addr)->sin_addr)];
break;
}
if ( reqTypFam == AF_INET6 )
{
char tmp[INET6_ADDRSTRLEN];
inet_ntop(AF_INET6, &(((struct sockaddr_in6 *)pAddr->ifa_addr)->sin6_addr), tmp, INET6_ADDRSTRLEN);
ipAdr = [NSString stringWithUTF8String: tmp];
break;;
}
}
}
pAddr = pAddr->ifa_next;
}
freeifaddrs(pAddrs);
}
return( ipAdr );
}
我的问题:我是否可以通过编程方式获取所需信息,而无需等待20到40秒?