1 //
2 // CXNetworkSpeed.h
3 // CXNetworkSpeedDemo
4 //
5 // Created by xubaoaichiyu on 16/08/16.
6 // Copyright © 2016年 xubaoaichiyu All rights reserved.
7 //
8
9
10
11 #import <Foundation/Foundation.h>
12
13
14 @interface CXNetworkSpeed : NSObject
15
16 @property (nonatomic, copy, readonly) NSString * receivedNetworkSpeed;
17
18 @property (nonatomic, copy, readonly) NSString * sendNetworkSpeed;
19
20 + (instancetype)shareNetworkSpeed;
21
22 - (void)startMonitoringNetworkSpeed;
23
24 - (void)stopMonitoringNetworkSpeed;
25
26 @end
27
28
29
30 /**
31 * @{@"received":@"100kB/s"}
32 */
33 FOUNDATION_EXTERN NSString *const kNetworkReceivedSpeedNotification;
34
35 /**
36 * @{@"send":@"100kB/s"}
37 */
38 FOUNDATION_EXTERN NSString *const kNetworkSendSpeedNotification;
1 //
2 // CXNetworkSpeed.m
3 // CXNetworkSpeedDemo
4 //
5 // Created by xubaoaichiyu on 16/08/16.
6 // Copyright © 2016年 xubaoaichiyu All rights reserved.
7 //
8
9 #import "CXNetworkSpeed.h"
10 #include <arpa/inet.h>
11 #include <net/if.h>
12 #include <ifaddrs.h>
13 #include <net/if_dl.h>
14
15 /**
16 * @{@"received":@"100kB/s"}
17 */
18 NSString *const kNetworkReceivedSpeedNotification = @"kNetworkReceivedSpeedNotification";
19
20 /**
21 * @{@"send":@"100kB/s"}
22 */
23 NSString *const kNetworkSendSpeedNotification = @"kNetworkSendSpeedNotification";
24
25 @interface CXNetworkSpeed ()
26 {
27 uint32_t _iBytes;
28 uint32_t _oBytes;
29 uint32_t _allFlow;
30 uint32_t _wifiIBytes;
31 uint32_t _wifiOBytes;
32 uint32_t _wifiFlow;
33 uint32_t _wwanIBytes;
34 uint32_t _wwanOBytes;
35 uint32_t _wwanFlow;
36 }
37
38 @property (nonatomic, copy) NSString * receivedNetworkSpeed;
39
40 @property (nonatomic, copy) NSString * sendNetworkSpeed;
41
42 @property (nonatomic, strong) NSTimer * timer;
43
44 @end
45
46 @implementation CXNetworkSpeed
47
48 static CXNetworkSpeed * instance = nil;
49
50 + (instancetype)shareNetworkSpeed{
51 if(instance == nil){
52 static dispatch_once_t onceToken ;
53 dispatch_once(&onceToken, ^{
54 instance = [[self alloc] init] ;
55 }) ;
56 }
57 return instance;
58
59 }
60
61 + (instancetype)allocWithZone:(struct _NSZone *)zone{
62
63 if(instance == nil){
64 static dispatch_once_t onceToken;
65 dispatch_once(&onceToken, ^{
66
67 instance = [super allocWithZone:zone];
68
69 });
70 }
71 return instance;
72 }
73
74 -(instancetype)init{
75
76 static dispatch_once_t onceToken;
77 dispatch_once(&onceToken, ^{
78 instance = [super init];
79 _iBytes = _oBytes = _allFlow = _wifiIBytes = _wifiOBytes = _wifiFlow = _wwanIBytes = _wwanOBytes = _wwanFlow = 0;
80 });
81 return instance;
82
83 }
84
85 - (void)startMonitoringNetworkSpeed{
86 if(_timer)
87 [self stopMonitoringNetworkSpeed];
88 _timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(netSpeedNotification) userInfo:nil repeats:YES];
89 }
90
91 - (void)stopMonitoringNetworkSpeed{
92 if ([_timer isValid]) {
93 [_timer invalidate];