擷取手機使用流量存在幾個問題:
①iOS是無法像Android一樣監聽到開機廣播和關機廣播的,立刻關機再開機,監測的移動網路下流量會預設清空。
②應用在後台運行時,突然被殺死,無法對流量統計,需要在應用進入後台時先儲存流量使用方式
③如果使用者第一次開啟流量統計軟體是在2月份,當第3個月開啟時,應該對2月份使用的流量清零。但是問題來了,我們所能擷取的是從監測開始,消耗的總流量。套餐流量為每個月1000M,如果2月份消耗了200M流量,3月消耗了300M流量,我們無法判斷3月份流量剩餘情況,我們獲得的使用流量為500M。建議當新的一個月開始時,使用者首次開啟app,提醒使用者重新設定剩餘流量。
注意:請在真機上測試該代碼
核心代碼:
HTTraffic.h
#import <Foundation/Foundation.h>@interface HTTraffic : NSObject+ (NSDictionary *)getTrafficMonitorings;@end
HTTraffic.m
#import "HTTraffic.h"#include <arpa/inet.h>#include <net/if.h>#include <ifaddrs.h>#include <net/if_dl.h>@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