iOS开发监测手机流量使用情况

获取手机使用流量存在几个问题:
①iOS是无法像Android一样监听到开机广播和关机广播的,立刻关机再开机,监测的移动网络下流量会默认清空。
②应用在后台运行时,突然被杀死,无法对流量统计,需要在应用进入后台时先保存流量使用情况
③如果用户第一次打开流量统计软件是在2月份,当第3个月打开时,应该对2月份使用的流量清零。但是问题来了,我们所能获取的是从监测开始,消耗的总流量。套餐流量为每个月1000M,如果2月份消耗了200M流量,3月消耗了300M流量,我们无法判断3月份流量剩余情况,我们获得的使用流量为500M。建议当新的一个月开始时,用户首次打开app,提醒用户重新设置剩余流量。

注意:请在真机上测试该代码
核心代码:
HTTraffic.h

#import 

@interface HTTraffic : NSObject

+ (NSDictionary *)getTrafficMonitorings;

@end

HTTraffic.m

#import "HTTraffic.h"
#include 
#include 
#include 
#include 

@implementation HTTraffic

/**
 *  WiFiSent WiFi发送流量
 *  WiFiReceived WiFi接收流量
 *  WWANSent 移动网络发送流量
 *  WWANReceived 移动网络接收流量
 */
+ (NSDictionary *)getTrafficMonitorings {
    NSDictionary * trafficDict = [[NSDictionary alloc] init];
    BOOL success;
    struct ifaddrs *addrs;
    const struct ifaddrs *cursor;
    const struct if_data *networkStatisc;
    int WiFiSent = 0;
    int WiFiReceived = 0;
    int WWANSent = 0;
    int WWANReceived = 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) {
                //wifi消耗流量
                if ([name hasPrefix:@"en"]) {
                    networkStatisc = (const struct if_data *) cursor->ifa_data;
                    WiFiSent+=networkStatisc->ifi_obytes;
                    WiFiReceived+=networkStatisc->ifi_ibytes;
                }

                //移动网络消耗流量
                if ([name hasPrefix:@"pdp_ip0"]) {
                    networkStatisc = (const struct if_data *) cursor->ifa_data;
                    WWANSent+=networkStatisc->ifi_obytes;
                    WWANReceived+=networkStatisc->ifi_ibytes;
                }
            }
            cursor = cursor->ifa_next;
        }
        freeifaddrs(addrs);
    }
    NSString *WiFiSentTraffic = [NSString stringWithFormat:@"%d",WiFiSent];
    NSString *WiFiReceivedTraffic = [NSString stringWithFormat:@"%d",WiFiReceived];
    NSString *WiFiTotalTraffic = [NSString stringWithFormat:@"%d",WiFiSent + WiFiReceived];
    NSString *WWANSentTraffic = [NSString stringWithFormat:@"%d",WWANSent];
    NSString *WWANReceivedTraffic = [NSString stringWithFormat:@"%d",WWANReceived];
    NSString *WWANTotalTraffic = [NSString stringWithFormat:@"%d",WWANSent+WWANReceived];
    trafficDict = @{
                    @"WiFiSentTraffic":WiFiSentTraffic,
                    @"WiFiReceivedTraffic":WiFiReceivedTraffic,
                    @"WiFiTotalTraffic":WiFiTotalTraffic,
                    @"WWANSentTraffic":WWANSentTraffic,
                    @"WWANReceivedTraffic":WWANReceivedTraffic,
                    @"WWANTotalTraffic":WWANTotalTraffic
                    };

    return trafficDict;
}

@end

流量监测demo

你可能感兴趣的:(iOS开发笔记,流量监测,获取手机流量,iOS流量统计)