我在这个主题上进行了搜索,但发现很少有有用的详细信息。根据这些信息,我尝试编写以下代码。
注意:在将此帖子与其他帖子进行比较之前,请比较共享的详细信息,而不仅仅是主题。
- (NSArray *)getDataCountersForType:(int)type {
BOOL success;
struct ifaddrs *addrs = nil;
const struct ifaddrs *cursor = nil;
const struct sockaddr_dl *dlAddr = nil;
const struct if_data *networkStatisc = nil;
int dataSent = 0;
int dataReceived = 0;
success = getifaddrs(&addrs) == 0;
if (success) {
cursor = addrs;
while (cursor != NULL) {
if (cursor->ifa_addr->sa_family == AF_LINK) {
dlAddr = (const struct sockaddr_dl *) cursor->ifa_addr;
networkStatisc = (const struct if_data *) cursor->ifa_data;
if (type == WiFi) {
dataSent += networkStatisc->ifi_opackets;
dataReceived += networkStatisc->ifi_ipackets;
}
else if (type == WWAN) {
dataSent += networkStatisc->ifi_obytes;
dataReceived += networkStatisc->ifi_ibytes;
}
}
cursor = cursor->ifa_next;
}
freeifaddrs(addrs);
}
return [NSArray arrayWithObjects:[NSNumber numberWithInt:dataSent], [NSNumber numberWithInt:dataReceived], nil];
}
这段代码收集了 iPhone 设备的网络使用情况(不仅限于我的应用程序)。
现在,如果我通过 WiFi 或 3G 使用互联网,我只能在 ifi_obytes
(发送)和 ifi_ibytes
(接收)中获取数据(字节),但我认为我应该在 ifi_opackets
和 ifi_ipackets
中获取 WiFi 的使用情况。
另外我要补充的是,如果我连接到 WiFi 网络,但没有使用互联网,我仍然会得到添加到 ifi_obytes
和 ifi_ibytes
的值。
也许我的实现或理解出了问题。需要有人帮我解决。
编辑:我尝试了使用 AF_INET
(sockaddr_in
而不是 sockaddr_dl
)代替 AF_LINK
。这导致了应用程序崩溃。