開發(fā)中用到獲取網(wǎng)速的地方,應(yīng)該就兩種:
1里逆、下載速度进胯,這種可以直接在接受數(shù)據(jù)的地方統(tǒng)計(jì)計(jì)算。這個(gè)就不講了原押。
2胁镐、獲取手機(jī)網(wǎng)卡的數(shù)據(jù),可以監(jiān)控網(wǎng)卡的進(jìn)出流量诸衔,下面就是盯漂。
代碼:.m文件實(shí)現(xiàn)
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(getInternetface) userInfo:nil repeats:YES];
[timer fireDate];
}
- (void)getInternetface {
long long hehe = [self getInterfaceBytes];
NSLog(@"hehe:%lld",hehe);
}
/*獲取網(wǎng)絡(luò)流量信息*/
- (long long) getInterfaceBytes
{
struct ifaddrs *ifa_list = 0, *ifa;
if (getifaddrs(&ifa_list) == -1)
{
return 0;
}
uint32_t iBytes = 0;
uint32_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;
/* Not a loopback device. */
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;
}
}
freeifaddrs(ifa_list);
NSLog(@"\n[getInterfaceBytes-Total]%d,%d",iBytes,oBytes);
return iBytes + oBytes;
}
@end
getInternetface方法就是返回的當(dāng)前網(wǎng)卡流量。再根據(jù)你的產(chǎn)品需求做數(shù)據(jù)轉(zhuǎn)換并定制ui署隘。