美文网首页
IOS流量统计

IOS流量统计

作者: 严木木 | 来源:发表于2017-02-22 16:53 被阅读957次

    最近做视频遇到了一个需求就是将流量放在视频上方展示  


    于是2开始各种百度最后终于解决直接上代码吧

    #include. 

    #include

    #include

    NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(getInternetface) userInfo:nil repeats:YES];

    [timer fireDate];

    - (void)getInternetface {

    long newBytes = [self getGprsWifiFlowIOBytes];

    if ( _oldBytes > 0) {

    _totalBytes = _totalBytes + newBytes - _oldBytes;

    _traffic.text = [NSString stringWithFormat:@"流量:%@ ,码率%@/s",[self zhuanHuan:_totalBytes],[self zhuanHuan:newBytes - _oldBytes]];

    }

    _oldBytes = newBytes;

    }

    /*获取网络流量信息*/

    -(long long )getGprsWifiFlowIOBytes{

    struct ifaddrs *ifa_list = 0, *ifa;

    if (getifaddrs(&ifa_list) == -1) {

    return 0;

    }

    uint64_t iBytes = 0;

    uint64_t oBytes = 0;

    for (ifa = ifa_list; ifa; ifa = ifa->ifa_next) {

    if (AF_LINK != ifa->ifa_addr->sa_family)

    continue;

    if (!(ifa->ifa_flags & IFF_UP) && !(ifa->ifa_flags & IFF_RUNNING))

    continue;

    if (ifa->ifa_data == 0)

    continue;

    //Wifi

    if (strncmp(ifa->ifa_name, "lo", 2)) {

    struct if_data *if_data = (struct if_data *)ifa->ifa_data;

    iBytes += if_data->ifi_ibytes;

    oBytes += if_data->ifi_obytes;

    //          NSLog(@"%s :iBytes is %d, oBytes is %d", ifa->ifa_name, iBytes, oBytes);

    }

    //3G或者GPRS

    if (!strcmp(ifa->ifa_name, "pdp_ip0")){

    struct if_data *if_data = (struct if_data *)ifa->ifa_data;

    iBytes += if_data->ifi_ibytes;

    oBytes += if_data->ifi_obytes;

    //            NSLog(@"%s :iBytes is %d, oBytes is %d",ifa->ifa_name, iBytes, oBytes);

    }

    }

    freeifaddrs(ifa_list);

    uint64_t bytes = 0;

    bytes = iBytes + oBytes;

    //    NSLog(@"返回 ==== %llu ",bytes);

    return bytes;

    }

    //将bytes单位转换

    -(NSString *)zhuanHuan:(long)bytes{

    if(bytes < 1024){ // B

    return [NSString stringWithFormat:@"%ldB", bytes];

    }else if(bytes >= 1024 && bytes < 1024 * 1024){// KB

    return [NSString stringWithFormat:@"%.1fKB", (double)bytes / 1024];

    }else if(bytes >= 1024 * 1024 && bytes < 1024 * 1024 * 1024){// MB

    return [NSString stringWithFormat:@"%.2fMB", (double)bytes / (1024 * 1024)];

    }else{ // GB

    return [NSString stringWithFormat:@"%.3fGB", (double)bytes / (1024 * 1024 * 1024)];

    }

    }



    相关文章

      网友评论

          本文标题:IOS流量统计

          本文链接:https://www.haomeiwen.com/subject/kaemwttx.html