大家都知道,iOS系统中没有实时流量监控的功能,尤其是最近我们在做直播功能的时候需要知道不同的分辨率我们的推拉流过程中的实时网速,还有一个是实时的查看APP的内存使用情况。
1、实时流量监控
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
| - (NSString *)getDataCounters { BOOL success; struct ifaddrs *addrs; const struct ifaddrs *cursor; const struct if_data *networkStatisc; static int SZNetSent = 0; static int SZNetReceived = 0; int NetSent = 0; int NetReceived = 0; NSString *name=[[NSString alloc]init]; success = getifaddrs(&addrs) == 0; if (success) { cursor = addrs; while (cursor != NULL) { name=[NSString stringWithFormat: @"%s",cursor->ifa_name]; if (cursor->ifa_addr->sa_family == AF_LINK) { if ([name hasPrefix:@"en"]) { networkStatisc = (const struct if_data *) cursor ->ifa_data; NetSent+=networkStatisc->ifi_obytes; NetReceived+=networkStatisc- >ifi_ibytes; } if ([name hasPrefix:@"pdp_ip"]) { networkStatisc = (const struct if_data *) cursor ->ifa_data; NetSent+=networkStatisc->ifi_obytes; NetReceived+= networkStatisc->ifi_ibytes; } } cursor = cursor->ifa_next; } freeifaddrs(addrs); }
CGFloat CZNetSent = NetSent - SZNetSent; CGFloat CZNetReceived = NetReceived - SZNetReceived; SZNetSent = NetSent; SZNetReceived = NetReceived; NSString *str = [NSString stringWithFormat:@"%3.2f - %3.2f KB/s", CZNetSent / 1024., CZNetReceived / 1024.]; return str; }
|
2、APP内存使用情况
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| 1、获取APP已使用的内存
vm_size_t usedMemory(void) { struct task_basic_info info; mach_msg_type_number_t size = sizeof(info); kern_return_t kerr = task_info(mach_task_self(), TASK_BASIC_INFO, (task_info_t)&info, &size); return (kerr == KERN_SUCCESS) ? info.resident_size : 0; // size in bytes }
2、获取可以使用的内存 vm_size_t freeMemory(void) { mach_port_t host_port = mach_host_self(); mach_msg_type_number_t host_size = sizeof(vm_statistics_data_t) / sizeof(integer_t); vm_size_t pagesize; vm_statistics_data_t vm_stat; host_page_size(host_port, &pagesize); (void) host_statistics(host_port, HOST_VM_INFO, (host_info_t)&vm_stat, &host_size); return vm_stat.free_count * pagesize; }
|
经过测试这个方法与实际Xcode中显示的内存有一定的差距。不过在用于显示内存占用变化情况的时候还是可以使用的