iOS|iOS OC 监听当前wifi网速
思路:先获取到总的流量信息,然后用当前的总下行流量减去上一秒的下行流量得到网速!
【iOS|iOS OC 监听当前wifi网速】具体实现在以下三个方法!
//获取下行速度- (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=https://www.it610.com/article/=0)continue;
if(strncmp(ifa->ifa_name,"lo",2)) {structif_data*if_data = https://www.it610.com/article/(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/秒";
};
}
推荐阅读
- 2020-04-07vue中Axios的封装和API接口的管理
- iOS中的Block
- 记录iOS生成分享图片的一些问题,根据UIView生成固定尺寸的分享图片
- 2019-08-29|2019-08-29 iOS13适配那点事
- Hacking|Hacking with iOS: SwiftUI Edition - SnowSeeker 项目(一)
- iOS面试题--基础
- Quartz|Quartz 源码解析(四) —— QuartzScheduler和Listener事件监听
- 接口|axios接口报错-参数类型错误解决
- iOS|iOS 笔记之_时间戳 + DES 加密
- iOS,打Framework静态库