iOS OC 监听当前wifi网速

作者: 不会抽烟 | 来源:发表于2017-01-03 11:43 被阅读316次

    思路:先获取到总的流量信息,然后用当前的总下行流量减去上一秒的下行流量得到网速!

    具体实现在以下三个方法!

    //获取下行速度
    
    - (void)getByteRate {
    
      longlongintrate;
    
      longlongintcurrentBytes = [selfgetInterfaceBytes];
    
      if(self.lastBytes) {
    
      //用上当前的下行总流量减去上一秒的下行流量达到下行速录
    
      rate = currentBytes -self.lastBytes;
    
      }else{
    
      self.isFirstRate=NO;
    }
      //保存上一秒的下行总流量
      self.lastBytes= [selfgetInterfaceBytes];
    
      //格式化一下
      NSString*rateStr = [selfformatNetWork:rate];
    
      NSLog(@"当前网速%@",rateStr);
    
    self.playerControl.LoadingView.rateLabel.text = [NSStringstringWithFormat:@"%@",rateStr];
    }
    
    //获取数据流量详情
    
    - (longlongint)getInterfaceBytes {
    
      structifaddrs*ifa_list =0, *ifa;
    
      if(getifaddrs(&ifa_list) == -1) {
    
       return 0;
      }
    
      uint32_tiBytes =0;//下行
    
      uint32_toBytes =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;
    
      if(strncmp(ifa->ifa_name,"lo",2)) {
    
      structif_data*if_data = (structif_data*)ifa->ifa_data;
    
      iBytes += if_data->ifi_ibytes;
    
      oBytes += if_data->ifi_obytes;
      }
      }
    
      freeifaddrs(ifa_list);
      //返回下行的总流量
      returniBytes;
    }
    
    //格式化方法
    - (NSString*)formatNetWork:(longlongint)rate {
    
      if(rate <1024) {
    
      return[NSStringstringWithFormat:@"%lldB/秒", rate];
    
      }elseif(rate >=1024&& rate <1024*1024) {
    
      return[NSStringstringWithFormat:@"%.1fKB/秒", (double)rate /1024];
    
      }elseif(rate >=1024*1024&& rate <1024*1024*1024){
    
      return[NSStringstringWithFormat:@"%.2fMB/秒", (double)rate / (1024*1024)];
    
      }else{
      return@"10Kb/秒";
    };
    }
    

    相关文章

      网友评论

        本文标题:iOS OC 监听当前wifi网速

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