├── NMSample ├── NMSample.xcodeproj │ ├── project.pbxproj │ └── project.xcworkspace │ │ ├── contents.xcworkspacedata │ │ └── xcshareddata │ │ └── IDEWorkspaceChecks.plist ├── NMSample │ ├── AppDelegate.h │ ├── AppDelegate.m │ ├── Assets.xcassets │ │ ├── AppIcon.appiconset │ │ │ └── Contents.json │ │ └── Contents.json │ ├── Base.lproj │ │ ├── LaunchScreen.storyboard │ │ └── Main.storyboard │ ├── Classes │ │ ├── AFNetworkingVC.h │ │ ├── AFNetworkingVC.m │ │ ├── AFNetworkingVC.xib │ │ ├── ConfigViewController.h │ │ ├── ConfigViewController.m │ │ ├── ConfigViewController.xib │ │ ├── NSURLConnectionDownloadDelegate.h │ │ ├── NSURLConnectionDownloadDelegate.m │ │ ├── NSURLConnectionVC.h │ │ ├── NSURLConnectionVC.m │ │ ├── NSURLConnectionVC.xib │ │ ├── NSURLSessionVC.h │ │ ├── NSURLSessionVC.m │ │ ├── NSURLSessionVC.xib │ │ ├── ViewController.h │ │ ├── ViewController.m │ │ ├── WebViewController.h │ │ └── WebViewController.m │ ├── Frameworks │ │ └── AFNetworking.framework │ │ │ ├── AFNetworking │ │ │ ├── Headers │ │ │ ├── AFAutoPurgingImageCache.h │ │ │ ├── AFCompatibilityMacros.h │ │ │ ├── AFHTTPSessionManager.h │ │ │ ├── AFImageDownloader.h │ │ │ ├── AFNetworkActivityIndicatorManager.h │ │ │ ├── AFNetworkReachabilityManager.h │ │ │ ├── AFNetworking.h │ │ │ ├── AFSecurityPolicy.h │ │ │ ├── AFURLRequestSerialization.h │ │ │ ├── AFURLResponseSerialization.h │ │ │ ├── AFURLSessionManager.h │ │ │ ├── UIActivityIndicatorView+AFNetworking.h │ │ │ ├── UIButton+AFNetworking.h │ │ │ ├── UIImage+AFNetworking.h │ │ │ ├── UIImageView+AFNetworking.h │ │ │ ├── UIProgressView+AFNetworking.h │ │ │ ├── UIRefreshControl+AFNetworking.h │ │ │ └── UIWebView+AFNetworking.h │ │ │ ├── Info.plist │ │ │ └── Modules │ │ │ └── module.modulemap │ ├── Info.plist │ └── main.m └── NMSampleTests │ ├── Info.plist │ └── NMSampleTests.m ├── NetworkMonitor.xcworkspace ├── contents.xcworkspacedata └── xcshareddata │ └── IDEWorkspaceChecks.plist ├── NetworkMonitor ├── NetworkMonitor.xcodeproj │ ├── project.pbxproj │ └── project.xcworkspace │ │ ├── contents.xcworkspacedata │ │ └── xcshareddata │ │ └── IDEWorkspaceChecks.plist ├── NetworkMonitor │ ├── Info.plist │ ├── NMAOP │ │ ├── NMHooker.h │ │ ├── NMHooker.m │ │ ├── NMObjectDelegate.h │ │ ├── NMObjectDelegate.m │ │ ├── NMProxy.h │ │ ├── NMProxy.m │ │ ├── NMURLProtocol.h │ │ ├── NMURLProtocol.m │ │ ├── NSHTTPURLResponse+NM.h │ │ ├── NSHTTPURLResponse+NM.m │ │ ├── NSURLConnection+NM.h │ │ ├── NSURLConnection+NM.m │ │ ├── NSURLRequest+NM.h │ │ ├── NSURLRequest+NM.m │ │ ├── NSURLSession+NM.h │ │ └── NSURLSession+NM.m │ ├── NMCache │ │ ├── NMCache.h │ │ ├── NMCache.m │ │ ├── NMDataModel.h │ │ ├── NMDataModel.m │ │ ├── NMModelCommon.h │ │ └── NMModelCommon.m │ ├── NMCore │ │ ├── NMConfig.h │ │ ├── NMConfig.m │ │ ├── NMManager.h │ │ ├── NMManager.m │ │ ├── NSURL+NM.h │ │ ├── NSURL+NM.m │ │ └── NetworkMonitorDef.h │ ├── NMDatabase │ │ ├── DAO │ │ │ ├── BaseDAO.h │ │ │ ├── BaseDAO.m │ │ │ ├── NMDataDAO.h │ │ │ └── NMDataDAO.m │ │ ├── Model │ │ │ ├── NMData+CoreDataClass.h │ │ │ ├── NMData+CoreDataClass.m │ │ │ ├── NMData+CoreDataProperties.h │ │ │ └── NMData+CoreDataProperties.m │ │ └── NetworkMonitor.xcdatamodeld │ │ │ └── EagleEye.xcdatamodel │ │ │ └── contents │ ├── NMUtil │ │ ├── NMUtil.h │ │ ├── NMUtil.m │ │ ├── NSData+GZIP.h │ │ └── NSData+GZIP.m │ ├── NetworkMonitor.h │ └── NetworkMonitor.pch └── NetworkMonitorTests │ ├── Info.plist │ └── NetworkMonitorTests.m └── README.md /NMSample/NMSample.xcodeproj/project.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /NMSample/NMSample.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | IDEDidComputeMac32BitWarning 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /NMSample/NMSample/AppDelegate.h: -------------------------------------------------------------------------------- 1 | // 2 | // AppDelegate.h 3 | // NMSample 4 | // 5 | // Created by frog78 on 2018/8/16. 6 | // Copyright © 2018年 frog78. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @interface AppDelegate : UIResponder 12 | 13 | @property (strong, nonatomic) UIWindow *window; 14 | 15 | 16 | @end 17 | 18 | -------------------------------------------------------------------------------- /NMSample/NMSample/AppDelegate.m: -------------------------------------------------------------------------------- 1 | // 2 | // AppDelegate.m 3 | // NMSample 4 | // 5 | // Created by frog78 on 2018/8/16. 6 | // Copyright © 2018年 frog78. All rights reserved. 7 | // 8 | 9 | #import "AppDelegate.h" 10 | #import "ConfigViewController.h" 11 | 12 | @interface AppDelegate () 13 | 14 | @end 15 | 16 | @implementation AppDelegate 17 | 18 | 19 | - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { 20 | ConfigViewController *vc = [[ConfigViewController alloc] init]; 21 | self.window.rootViewController = [[UINavigationController alloc] initWithRootViewController:vc]; 22 | [self.window makeKeyAndVisible]; 23 | return YES; 24 | } 25 | 26 | 27 | - (void)applicationWillResignActive:(UIApplication *)application { 28 | // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. 29 | // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. 30 | } 31 | 32 | 33 | - (void)applicationDidEnterBackground:(UIApplication *)application { 34 | // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 35 | // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. 36 | } 37 | 38 | 39 | - (void)applicationWillEnterForeground:(UIApplication *)application { 40 | // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. 41 | } 42 | 43 | 44 | - (void)applicationDidBecomeActive:(UIApplication *)application { 45 | // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. 46 | } 47 | 48 | 49 | - (void)applicationWillTerminate:(UIApplication *)application { 50 | // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. 51 | } 52 | 53 | 54 | @end 55 | -------------------------------------------------------------------------------- /NMSample/NMSample/Assets.xcassets/AppIcon.appiconset/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "images" : [ 3 | { 4 | "idiom" : "iphone", 5 | "size" : "20x20", 6 | "scale" : "2x" 7 | }, 8 | { 9 | "idiom" : "iphone", 10 | "size" : "20x20", 11 | "scale" : "3x" 12 | }, 13 | { 14 | "idiom" : "iphone", 15 | "size" : "29x29", 16 | "scale" : "2x" 17 | }, 18 | { 19 | "idiom" : "iphone", 20 | "size" : "29x29", 21 | "scale" : "3x" 22 | }, 23 | { 24 | "idiom" : "iphone", 25 | "size" : "40x40", 26 | "scale" : "2x" 27 | }, 28 | { 29 | "idiom" : "iphone", 30 | "size" : "40x40", 31 | "scale" : "3x" 32 | }, 33 | { 34 | "idiom" : "iphone", 35 | "size" : "60x60", 36 | "scale" : "2x" 37 | }, 38 | { 39 | "idiom" : "iphone", 40 | "size" : "60x60", 41 | "scale" : "3x" 42 | }, 43 | { 44 | "idiom" : "ipad", 45 | "size" : "20x20", 46 | "scale" : "1x" 47 | }, 48 | { 49 | "idiom" : "ipad", 50 | "size" : "20x20", 51 | "scale" : "2x" 52 | }, 53 | { 54 | "idiom" : "ipad", 55 | "size" : "29x29", 56 | "scale" : "1x" 57 | }, 58 | { 59 | "idiom" : "ipad", 60 | "size" : "29x29", 61 | "scale" : "2x" 62 | }, 63 | { 64 | "idiom" : "ipad", 65 | "size" : "40x40", 66 | "scale" : "1x" 67 | }, 68 | { 69 | "idiom" : "ipad", 70 | "size" : "40x40", 71 | "scale" : "2x" 72 | }, 73 | { 74 | "idiom" : "ipad", 75 | "size" : "76x76", 76 | "scale" : "1x" 77 | }, 78 | { 79 | "idiom" : "ipad", 80 | "size" : "76x76", 81 | "scale" : "2x" 82 | }, 83 | { 84 | "idiom" : "ipad", 85 | "size" : "83.5x83.5", 86 | "scale" : "2x" 87 | }, 88 | { 89 | "idiom" : "ios-marketing", 90 | "size" : "1024x1024", 91 | "scale" : "1x" 92 | } 93 | ], 94 | "info" : { 95 | "version" : 1, 96 | "author" : "xcode" 97 | } 98 | } -------------------------------------------------------------------------------- /NMSample/NMSample/Assets.xcassets/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "info" : { 3 | "version" : 1, 4 | "author" : "xcode" 5 | } 6 | } -------------------------------------------------------------------------------- /NMSample/NMSample/Base.lproj/LaunchScreen.storyboard: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /NMSample/NMSample/Base.lproj/Main.storyboard: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /NMSample/NMSample/Classes/AFNetworkingVC.h: -------------------------------------------------------------------------------- 1 | // 2 | // AFNetworkingVC.h 3 | // NetworkMonitorSample 4 | // 5 | // Created by frog78 on 2018/4/28. 6 | // Copyright © 2018年 frog78. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @interface AFNetworkingVC : UIViewController 12 | 13 | @end 14 | -------------------------------------------------------------------------------- /NMSample/NMSample/Classes/AFNetworkingVC.xib: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 35 | 49 | 63 | 77 | 91 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 119 | 120 | 121 | 122 | 123 | 124 | 125 | 126 | 127 | 128 | 129 | 130 | 131 | 132 | -------------------------------------------------------------------------------- /NMSample/NMSample/Classes/ConfigViewController.h: -------------------------------------------------------------------------------- 1 | // 2 | // ConfigViewController.h 3 | // NetworkMonitorSample 4 | // 5 | // Created by frog78 on 2018/6/5. 6 | // Copyright © 2018年 frog78. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @interface ConfigViewController : UIViewController 12 | 13 | @end 14 | -------------------------------------------------------------------------------- /NMSample/NMSample/Classes/ConfigViewController.m: -------------------------------------------------------------------------------- 1 | // 2 | // ConfigViewController.m 3 | // NetworkMonitorSample 4 | // 5 | // Created by frog78 on 2018/6/5. 6 | // Copyright © 2018年 frog78. All rights reserved. 7 | // 8 | 9 | #import "ConfigViewController.h" 10 | #import "ViewController.h" 11 | #import 12 | 13 | const NSString *rtpKey = @"NetworkMonitor_rtpKey"; 14 | const NSString *rspKey = @"NetworkMonitor_rspKey"; 15 | const NSString *urlKey = @"NetworkMonitor_urlKey"; 16 | const NSString *urlWlKey = @"NetworkMonitor_urlWlKey"; 17 | const NSString *cmdWlKey = @"NetworkMonitor_cmdWlKey"; 18 | 19 | @interface ConfigViewController () { 20 | NMConfig *config; 21 | } 22 | @property (weak, nonatomic) IBOutlet UITextField *url; 23 | 24 | @property (weak, nonatomic) IBOutlet UITextField *urlWhiteList; 25 | @property (weak, nonatomic) IBOutlet UITextField *cmdWhiteList; 26 | @property (weak, nonatomic) IBOutlet UITextField *requestPara; 27 | @property (weak, nonatomic) IBOutlet UITextField *responsePara; 28 | @property (weak, nonatomic) IBOutlet UISwitch *sdkSwitch; 29 | @property (weak, nonatomic) IBOutlet UISwitch *logSwitch; 30 | @property (weak, nonatomic) IBOutlet UISwitch *modeSwitch; 31 | 32 | @end 33 | 34 | @implementation ConfigViewController 35 | 36 | - (void)viewDidLoad { 37 | [super viewDidLoad]; 38 | self.title = @"配置"; 39 | UIGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(viewClick)]; 40 | [self.view addGestureRecognizer:recognizer]; 41 | 42 | config = [[NMConfig alloc] init]; 43 | config.enableNetworkMonitor = YES; 44 | config.enableLog = NO; 45 | config.enableInterferenceMode = NO; 46 | NSDictionary *rtp = [[NSUserDefaults standardUserDefaults] objectForKey:(NSString *)rtpKey]; 47 | if (rtp) { 48 | self.requestPara.text = [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:rtp options:NSJSONWritingPrettyPrinted error:nil] encoding:NSUTF8StringEncoding]; 49 | } 50 | NSDictionary *rsp = [[NSUserDefaults standardUserDefaults] objectForKey:(NSString *)rspKey]; 51 | if (rsp) { 52 | self.responsePara.text = [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:rsp options:NSJSONWritingPrettyPrinted error:nil] encoding:NSUTF8StringEncoding]; 53 | } 54 | NSArray *urlWl = [[NSUserDefaults standardUserDefaults] objectForKey:(NSString *)urlWlKey]; 55 | if (urlWl) { 56 | self.urlWhiteList.text = [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:urlWl options:NSJSONWritingPrettyPrinted error:nil] encoding:NSUTF8StringEncoding]; 57 | } 58 | NSArray *cmdWl = [[NSUserDefaults standardUserDefaults] objectForKey:(NSString *)cmdWlKey]; 59 | if (cmdWl) { 60 | self.cmdWhiteList.text = [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:cmdWl options:NSJSONWritingPrettyPrinted error:nil] encoding:NSUTF8StringEncoding]; 61 | } 62 | NSString *url = [[NSUserDefaults standardUserDefaults] objectForKey:(NSString *)urlKey]; 63 | if (url) { 64 | self.url.text = url; 65 | } 66 | } 67 | 68 | - (IBAction)sdkSwitch:(id)sender { 69 | 70 | } 71 | 72 | - (IBAction)logSwitch:(id)sender { 73 | UISwitch *switchButton = (UISwitch *)sender; 74 | BOOL isButtonOn = [switchButton isOn]; 75 | if (isButtonOn) { 76 | config.enableLog = YES; 77 | } else { 78 | config.enableLog = NO; 79 | } 80 | } 81 | 82 | - (IBAction)modeSwitch:(id)sender { 83 | UISwitch *switchButton = (UISwitch *)sender; 84 | BOOL isButtonOn = [switchButton isOn]; 85 | if (isButtonOn) { 86 | config.enableInterferenceMode = YES; 87 | } else { 88 | config.enableInterferenceMode = NO; 89 | } 90 | } 91 | 92 | - (IBAction)startBtnClick:(id)sender { 93 | if (self.urlWhiteList.text) { 94 | config.urlWhiteList = [NSJSONSerialization JSONObjectWithData:[self.urlWhiteList.text dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:nil]; 95 | [[NSUserDefaults standardUserDefaults] setObject:config.urlWhiteList forKey:(NSString *)urlWlKey]; 96 | } 97 | 98 | if (self.cmdWhiteList.text) { 99 | config.cmdWhiteList = [NSJSONSerialization JSONObjectWithData:[self.cmdWhiteList.text dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:nil]; 100 | [[NSUserDefaults standardUserDefaults] setObject:config.cmdWhiteList forKey:(NSString *)cmdWlKey]; 101 | } 102 | 103 | if (self.requestPara.text) { 104 | NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:[self.requestPara.text dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:nil]; 105 | [[NSUserDefaults standardUserDefaults] setObject:dic forKey:(NSString *)rtpKey]; 106 | } 107 | 108 | if (self.responsePara.text) { 109 | NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:[self.responsePara.text dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:nil]; 110 | [[NSUserDefaults standardUserDefaults] setObject:dic forKey:(NSString *)rspKey]; 111 | } 112 | 113 | if (self.url.text) { 114 | [[NSUserDefaults standardUserDefaults] setObject:self.url.text forKey:(NSString *)urlKey]; 115 | } 116 | 117 | [[NMManager sharedNMManager] initConfig:config]; 118 | // NSArray *data = [[NMManager sharedNMManager] getAllData]; 119 | if (self.sdkSwitch.isOn) { 120 | [[NMManager sharedNMManager] start]; 121 | } else { 122 | [[NMManager sharedNMManager] stop]; 123 | } 124 | __weak typeof(self) weakSelf = self; 125 | [NMManager sharedNMManager].outputBlock = ^(NSString *traceId, NSDictionary *data) { 126 | [weakSelf alert:[[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:data options:NSJSONWritingPrettyPrinted error:nil] encoding:NSUTF8StringEncoding]]; 127 | }; 128 | // [[NMManager sharedNMManager] removeAll]; 129 | 130 | ViewController *vc = [[ViewController alloc] init]; 131 | [self.navigationController pushViewController:vc animated:YES]; 132 | } 133 | 134 | - (void)alert:(NSString *)str { 135 | UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"数据监控" message:str preferredStyle:UIAlertControllerStyleAlert]; 136 | UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) { 137 | 138 | }]; 139 | [alert addAction:action]; 140 | [self presentViewController:alert animated:YES completion:^{ 141 | 142 | }]; 143 | } 144 | 145 | - (void)viewClick { 146 | [self.urlWhiteList resignFirstResponder]; 147 | [self.cmdWhiteList resignFirstResponder]; 148 | [self.requestPara resignFirstResponder]; 149 | [self.responsePara resignFirstResponder]; 150 | } 151 | 152 | - (void)didReceiveMemoryWarning { 153 | [super didReceiveMemoryWarning]; 154 | // Dispose of any resources that can be recreated. 155 | } 156 | 157 | /* 158 | #pragma mark - Navigation 159 | 160 | // In a storyboard-based application, you will often want to do a little preparation before navigation 161 | - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { 162 | // Get the new view controller using [segue destinationViewController]. 163 | // Pass the selected object to the new view controller. 164 | } 165 | */ 166 | 167 | @end 168 | -------------------------------------------------------------------------------- /NMSample/NMSample/Classes/NSURLConnectionDownloadDelegate.h: -------------------------------------------------------------------------------- 1 | // 2 | // NSURLConnectionDownloadDelegate.h 3 | // NetworkMonitorSample 4 | // 5 | // Created by frog78 on 2018/6/7. 6 | // Copyright © 2018年 frog78. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @interface NSURLConnectionDownloadDelegate : NSObject 12 | 13 | @end 14 | -------------------------------------------------------------------------------- /NMSample/NMSample/Classes/NSURLConnectionDownloadDelegate.m: -------------------------------------------------------------------------------- 1 | // 2 | // NSURLConnectionDownloadDelegate.m 3 | // NetworkMonitorSample 4 | // 5 | // Created by frog78 on 2018/6/7. 6 | // Copyright © 2018年 frog78. All rights reserved. 7 | // 8 | 9 | #import "NSURLConnectionDownloadDelegate.h" 10 | 11 | @implementation NSURLConnectionDownloadDelegate 12 | 13 | #pragma mark-NSURLConnectionDownloadDelegate 14 | - (void)connection:(NSURLConnection *)connection didWriteData:(long long)bytesWritten totalBytesWritten:(long long)totalBytesWritten expectedTotalBytes:(long long) expectedTotalBytes { 15 | 16 | } 17 | 18 | - (void)connectionDidResumeDownloading:(NSURLConnection *)connection totalBytesWritten:(long long)totalBytesWritten expectedTotalBytes:(long long) expectedTotalBytes { 19 | 20 | } 21 | 22 | - (void)connectionDidFinishDownloading:(NSURLConnection *)connection destinationURL:(NSURL *) destinationURL { 23 | 24 | } 25 | 26 | 27 | @end 28 | -------------------------------------------------------------------------------- /NMSample/NMSample/Classes/NSURLConnectionVC.h: -------------------------------------------------------------------------------- 1 | // 2 | // NSURLConnectionVC.h 3 | // NetworkMonitorSample 4 | // 5 | // Created by frog78 on 2018/4/28. 6 | // Copyright © 2018年 frog78. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @interface NSURLConnectionVC : UIViewController 12 | 13 | @end 14 | -------------------------------------------------------------------------------- /NMSample/NMSample/Classes/NSURLConnectionVC.m: -------------------------------------------------------------------------------- 1 | // 2 | // NSURLConnectionVC.m 3 | // NetworkMonitorSample 4 | // 5 | // Created by frog78 on 2018/4/28. 6 | // Copyright © 2018年 frog78. All rights reserved. 7 | // 8 | 9 | #import "NSURLConnectionVC.h" 10 | #import "NSURLConnectionDownloadDelegate.h" 11 | #import 12 | 13 | extern NSString *rtpKey; 14 | extern NSString *rspKey; 15 | extern NSString *urlKey; 16 | 17 | //#define TEST_URL @"http://wthrcdn.etouch.cn/weather_mini?citykey=101010100" 18 | //#define TEST_URL @"https://www.google.com/" 19 | //#define TEST_URL @"https://wj.ahga.gov.cn/business-services/h5/remove-car-record" 20 | #define TEST_URL @"https://m.taobao.com" 21 | 22 | #define DOWNLOAD_URL @"http://download.voicecloud.cn/ygxt/20180605/85ee0f89-a95f-4424-8abc-4f6243ef79b2.zip" 23 | #define UPLOAD_URL @"http://test.cystorage.cycore.cn" 24 | 25 | @interface NSURLConnectionVC () { 26 | NSURLConnection *conn; 27 | NSDictionary *rtp; 28 | NSDictionary *rsp; 29 | NSString *urlString; 30 | } 31 | 32 | @end 33 | 34 | @implementation NSURLConnectionVC 35 | 36 | - (void)viewDidLoad { 37 | [super viewDidLoad]; 38 | self.title = @"NSURLConnection"; 39 | rtp = [[NSUserDefaults standardUserDefaults] objectForKey:rtpKey]; 40 | rsp = [[NSUserDefaults standardUserDefaults] objectForKey:rspKey]; 41 | urlString = [[NSUserDefaults standardUserDefaults] objectForKey:urlKey]; 42 | } 43 | 44 | //同步请求 45 | - (IBAction)synchronousRequest:(id)sender { 46 | 47 | NSURL *url; 48 | if (urlString && ![urlString isEqualToString:@""]) { 49 | url = [NSURL URLWithString:urlString]; 50 | } else { 51 | url = [NSURL URLWithString:TEST_URL]; 52 | } 53 | url.extendedParameter = rtp; 54 | NSURLRequest *request = [NSURLRequest requestWithURL:url]; 55 | 56 | NSHTTPURLResponse *response = nil; 57 | NSError *error = nil; 58 | 59 | [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; 60 | NSString *traceId = response.allHeaderFields[HEAD_KEY_EETRACEID]; 61 | [[NMManager sharedNMManager] setExtendedParameter:rsp traceId:traceId]; 62 | if ([[NMManager sharedNMManager] getConfig].enableInterferenceMode) { 63 | [[NMManager sharedNMManager] finishColection:traceId]; 64 | } 65 | } 66 | 67 | //异步请求 68 | - (IBAction)asynchronousRequest:(id)sender { 69 | NSURL *url; 70 | if (urlString && ![urlString isEqualToString:@""]) { 71 | url = [NSURL URLWithString:urlString]; 72 | } else { 73 | url = [NSURL URLWithString:TEST_URL]; 74 | } 75 | NSURLRequest *request = [NSURLRequest requestWithURL:url]; 76 | url.extendedParameter = rtp; 77 | [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) { 78 | NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response; 79 | NSString *traceId = httpResponse.allHeaderFields[HEAD_KEY_EETRACEID]; 80 | [[NMManager sharedNMManager] setExtendedParameter:rsp traceId:traceId]; 81 | if ([[NMManager sharedNMManager] getConfig].enableInterferenceMode) { 82 | [[NMManager sharedNMManager] finishColection:traceId]; 83 | } 84 | }]; 85 | } 86 | 87 | //代理方式请求 88 | - (IBAction)connectionStart:(id)sender { 89 | NSURL *url; 90 | if (urlString && ![urlString isEqualToString:@""]) { 91 | url = [NSURL URLWithString:urlString]; 92 | } else { 93 | url = [NSURL URLWithString:TEST_URL]; 94 | } 95 | url.extendedParameter = rtp; 96 | NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; 97 | request.HTTPMethod = @"get"; 98 | // 第一种代理方式 99 | conn = [[NSURLConnection alloc] initWithRequest:request delegate:self]; 100 | // 第二种代理方式 101 | // conn = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES]; 102 | //在startImmediately为NO时,调用该方法控制网络请求的发送 103 | [conn start]; 104 | 105 | // 第三种代理方式 106 | //设置代理的第三种方式:使用类方法设置代理,会自动发送网络请求 107 | // conn = [NSURLConnection connectionWithRequest:request delegate:self]; 108 | } 109 | 110 | - (IBAction)downloadStart:(id)sender { 111 | NSURL *url; 112 | if (urlString && ![urlString isEqualToString:@""]) { 113 | url = [NSURL URLWithString:urlString]; 114 | } else { 115 | url = [NSURL URLWithString:DOWNLOAD_URL]; 116 | } 117 | url.extendedParameter = rtp; 118 | NSURLRequest *request = [NSURLRequest requestWithURL:url]; 119 | // 第一种代理方式 120 | // conn = [[NSURLConnection alloc] initWithRequest:request delegate:self]; 121 | // 第二种代理方式 122 | conn = [[NSURLConnection alloc] initWithRequest:request delegate:[NSURLConnectionDownloadDelegate new] startImmediately:YES]; 123 | } 124 | - (IBAction)downloadCancel:(id)sender { 125 | [conn cancel]; 126 | } 127 | 128 | - (IBAction)uploadStart:(id)sender { 129 | // 请求的Url 130 | NSURL *url = [NSURL URLWithString:UPLOAD_URL]; 131 | url.extendedParameter = rtp; 132 | NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; 133 | [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; 134 | [request setValue:@"28" forHTTPHeaderField:@"Content-Length"]; 135 | [request setCachePolicy:NSURLRequestUseProtocolCachePolicy]; 136 | [request setHTTPMethod:@"POST"]; 137 | // 设置ContentType 138 | NSString *contentType = @"multipart/form-data"; 139 | [request setValue:contentType forHTTPHeaderField: @"Content-Type"]; 140 | NSString *filePath = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"pdf"]; 141 | NSData *httpBody = [self createBodyWithBoundary:@"" parameters:@{} paths:@[filePath] fieldName:@"file"]; 142 | [request setHTTPBody:httpBody]; 143 | conn = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES]; 144 | } 145 | 146 | - (IBAction)uploadCancel:(id)sender { 147 | [conn cancel]; 148 | } 149 | 150 | #pragma mark-NSURLConnectionDelegate 151 | - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { 152 | NSMutableURLRequest *mrq = (NSMutableURLRequest *)connection.originalRequest; 153 | NSString *traceId = mrq.allHTTPHeaderFields[HEAD_KEY_EETRACEID]; 154 | if ([[NMManager sharedNMManager] getConfig].enableInterferenceMode) { 155 | [[NMManager sharedNMManager] finishColection:traceId]; 156 | } 157 | } 158 | 159 | #pragma mark-NSURLConnectionDataDelegate 160 | //- (nullable NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(nullable NSURLResponse *)response { 161 | // return request; 162 | //} 163 | 164 | - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { 165 | NSMutableURLRequest *mrq = (NSMutableURLRequest *)connection.originalRequest; 166 | NSString *traceId = mrq.allHTTPHeaderFields[HEAD_KEY_EETRACEID]; 167 | [[NMManager sharedNMManager] setExtendedParameter:rsp traceId:traceId]; 168 | if ([[NMManager sharedNMManager] getConfig].enableInterferenceMode) { 169 | [[NMManager sharedNMManager] finishColection:traceId]; 170 | } 171 | } 172 | 173 | //- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { 174 | // NSLog(@"EE---->%@", [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]); 175 | //} 176 | // 177 | //- (void)connection:(NSURLConnection *)connection didSendBodyData:(NSInteger)bytesWritten 178 | // totalBytesWritten:(NSInteger)totalBytesWritten 179 | //totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite { 180 | // 181 | //} 182 | 183 | 184 | //- (void)connectionDidFinishLoading:(NSURLConnection *)connection { 185 | // 186 | //} 187 | 188 | - (NSData *)createBodyWithBoundary:(NSString *)boundary 189 | parameters:(NSDictionary *)parameters 190 | paths:(NSArray *)paths 191 | fieldName:(NSString *)fieldName { 192 | NSMutableData *httpBody = [NSMutableData data]; 193 | 194 | // 文本参数 195 | [parameters enumerateKeysAndObjectsUsingBlock:^(NSString *parameterKey, NSString *parameterValue, BOOL *stop) { 196 | [httpBody appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]]; 197 | [httpBody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", parameterKey] dataUsingEncoding:NSUTF8StringEncoding]]; 198 | [httpBody appendData:[[NSString stringWithFormat:@"%@\r\n", parameterValue] dataUsingEncoding:NSUTF8StringEncoding]]; 199 | }]; 200 | 201 | // 本地文件的NSData 202 | for (NSString *path in paths) { 203 | NSString *filename = [path lastPathComponent]; 204 | NSData *data = [NSData dataWithContentsOfFile:path]; 205 | 206 | [httpBody appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]]; 207 | [httpBody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\n", fieldName, filename] dataUsingEncoding:NSUTF8StringEncoding]]; 208 | [httpBody appendData:data]; 209 | [httpBody appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]]; 210 | } 211 | 212 | [httpBody appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]]; 213 | return httpBody; 214 | } 215 | 216 | 217 | - (void)didReceiveMemoryWarning { 218 | [super didReceiveMemoryWarning]; 219 | // Dispose of any resources that can be recreated. 220 | } 221 | 222 | 223 | @end 224 | -------------------------------------------------------------------------------- /NMSample/NMSample/Classes/NSURLSessionVC.h: -------------------------------------------------------------------------------- 1 | // 2 | // NSURLSessionVC.h 3 | // NetworkMonitorSample 4 | // 5 | // Created by frog78 on 2018/4/28. 6 | // Copyright © 2018年 frog78. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @interface NSURLSessionVC : UIViewController 12 | 13 | @end 14 | -------------------------------------------------------------------------------- /NMSample/NMSample/Classes/NSURLSessionVC.m: -------------------------------------------------------------------------------- 1 | // 2 | // NSURLSessionVC.m 3 | // NetworkMonitorSample 4 | // 5 | // Created by frog78 on 2018/4/28. 6 | // Copyright © 2018年 frog78. All rights reserved. 7 | // 8 | 9 | #import "NSURLSessionVC.h" 10 | #import 11 | 12 | extern NSString *rtpKey; 13 | extern NSString *rspKey; 14 | extern NSString *urlKey; 15 | 16 | //#define TEST_URL @"http://download.voicecloud.cn/ygxt/20180605/85ee0f89-a95f-4424-8abc-4f6243ef79b2.zip" 17 | //#define TEST_URL @"https://wj.ahga.gov.cn/business-services/h5/remove-car-record" 18 | #define TEST_URL @"https://h5.m.taobao.com" 19 | 20 | #define DOWNLOAD_URL @"http://download.voicecloud.cn/ygxt/20180605/85ee0f89-a95f-4424-8abc-4f6243ef79b2.zip" 21 | 22 | #define UPLOAD_URL @"http://test.cystorage.cycore.cn" 23 | 24 | @interface NSURLSessionVC () { 25 | NSURLSessionTask *task1; 26 | NSDictionary *rtp; 27 | NSDictionary *rsp; 28 | NSString *urlString; 29 | } 30 | 31 | @end 32 | 33 | @implementation NSURLSessionVC 34 | 35 | - (void)viewDidLoad { 36 | [super viewDidLoad]; 37 | self.title = @"NSURLSession"; 38 | rtp = [[NSUserDefaults standardUserDefaults] objectForKey:rtpKey]; 39 | rsp = [[NSUserDefaults standardUserDefaults] objectForKey:rspKey]; 40 | urlString = [[NSUserDefaults standardUserDefaults] objectForKey:urlKey]; 41 | } 42 | 43 | - (IBAction)get:(id)sender { 44 | 45 | NSURL *url; 46 | if (urlString && ![urlString isEqualToString:@""]) { 47 | url = [NSURL URLWithString:urlString]; 48 | } else { 49 | url = [NSURL URLWithString:TEST_URL]; 50 | } 51 | url.extendedParameter = rtp; 52 | NSURLRequest *request = [NSURLRequest requestWithURL:url]; 53 | NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration]; 54 | NSURLSession *session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:nil]; 55 | // NSURLSession *session = [NSURLSession sessionWithConfiguration:config]; 56 | 57 | NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *_Nullable data, NSURLResponse *_Nullable response, NSError * _Nullable error) { 58 | NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response; 59 | NSString *traceId = httpResponse.allHeaderFields[HEAD_KEY_EETRACEID]; 60 | [[NMManager sharedNMManager] setExtendedParameter:self->rsp traceId:traceId]; 61 | if ([[NMManager sharedNMManager] getConfig].enableInterferenceMode) { 62 | [[NMManager sharedNMManager] finishColection:traceId]; 63 | } 64 | [session invalidateAndCancel]; 65 | }]; 66 | [task resume]; 67 | } 68 | 69 | - (IBAction)post:(id)sender { 70 | NSURL *url; 71 | if (urlString && ![urlString isEqualToString:@""]) { 72 | url = [NSURL URLWithString:urlString]; 73 | } else { 74 | url = [NSURL URLWithString:TEST_URL]; 75 | } 76 | url.extendedParameter = rtp; 77 | NSURLRequest *request = [NSURLRequest requestWithURL:url]; 78 | NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration]; 79 | NSURLSession *session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:nil]; 80 | // NSURLSession *session = [NSURLSession sessionWithConfiguration:config]; 81 | NSURLSessionDataTask *task = [session dataTaskWithRequest:request]; 82 | [task resume]; 83 | } 84 | 85 | - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task 86 | didCompleteWithError:(nullable NSError *)error { 87 | NSMutableURLRequest *mrq = (NSMutableURLRequest *)task.originalRequest; 88 | NSString *traceId = mrq.allHTTPHeaderFields[HEAD_KEY_EETRACEID]; 89 | [[NMManager sharedNMManager] setExtendedParameter:rsp traceId:traceId]; 90 | if ([[NMManager sharedNMManager] getConfig].enableInterferenceMode) { 91 | [[NMManager sharedNMManager] finishColection:traceId]; 92 | } 93 | [session invalidateAndCancel]; 94 | } 95 | 96 | 97 | - (IBAction)downloadStart:(id)sender { 98 | NSURL *url; 99 | if (urlString && ![urlString isEqualToString:@""]) { 100 | url = [NSURL URLWithString:urlString]; 101 | } else { 102 | url = [NSURL URLWithString:DOWNLOAD_URL]; 103 | } 104 | url.extendedParameter = rtp; 105 | NSURLRequest *request = [NSURLRequest requestWithURL:url]; 106 | NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration]; 107 | NSURLSession *session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:nil]; 108 | //方式一:代理 109 | task1 = [session downloadTaskWithRequest:request]; 110 | [task1 resume]; 111 | //方式二:block 112 | // task1 = [session downloadTaskWithRequest:request completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) { 113 | // 114 | // }]; 115 | } 116 | 117 | 118 | - (IBAction)downloadCancel:(id)sender { 119 | [task1 cancel]; 120 | } 121 | 122 | - (IBAction)uploadStart:(id)sender { 123 | // 请求的Url 124 | NSURL *url = [NSURL URLWithString:UPLOAD_URL]; 125 | url.extendedParameter = rtp; 126 | NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; 127 | [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; 128 | [request setValue:@"28" forHTTPHeaderField:@"Content-Length"]; 129 | [request setCachePolicy:NSURLRequestUseProtocolCachePolicy]; 130 | [request setHTTPMethod:@"POST"]; 131 | NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration]; 132 | NSURLSession *session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:nil]; 133 | 134 | // 设置ContentType 135 | NSString *contentType = @"multipart/form-data"; 136 | [request setValue:contentType forHTTPHeaderField: @"Content-Type"]; 137 | NSString *filePath = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"pdf"]; 138 | NSData *httpBody = [self createBodyWithBoundary:@"" parameters:@{} paths:@[filePath] fieldName:@"file"]; 139 | task1 = [session uploadTaskWithRequest:request fromData:httpBody]; 140 | // task1 = [session uploadTaskWithRequest:request fromData:httpBody completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { 141 | // if (error) { 142 | // NSLog(@"error = %@", error); 143 | // } 144 | // }]; 145 | // task1 = [session uploadTaskWithRequest:request fromFile:[NSURL URLWithString:filePath] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) { 146 | // 147 | // }]; 148 | [task1 resume]; 149 | } 150 | 151 | - (IBAction)uploadCancel:(id)sender { 152 | [task1 cancel]; 153 | } 154 | 155 | - (NSData *)createBodyWithBoundary:(NSString *)boundary 156 | parameters:(NSDictionary *)parameters 157 | paths:(NSArray *)paths 158 | fieldName:(NSString *)fieldName { 159 | NSMutableData *httpBody = [NSMutableData data]; 160 | 161 | // 文本参数 162 | [parameters enumerateKeysAndObjectsUsingBlock:^(NSString *parameterKey, NSString *parameterValue, BOOL *stop) { 163 | [httpBody appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]]; 164 | [httpBody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", parameterKey] dataUsingEncoding:NSUTF8StringEncoding]]; 165 | [httpBody appendData:[[NSString stringWithFormat:@"%@\r\n", parameterValue] dataUsingEncoding:NSUTF8StringEncoding]]; 166 | }]; 167 | 168 | // 本地文件的NSData 169 | for (NSString *path in paths) { 170 | NSString *filename = [path lastPathComponent]; 171 | NSData *data = [NSData dataWithContentsOfFile:path]; 172 | 173 | [httpBody appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]]; 174 | [httpBody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\n", fieldName, filename] dataUsingEncoding:NSUTF8StringEncoding]]; 175 | [httpBody appendData:data]; 176 | [httpBody appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]]; 177 | } 178 | 179 | [httpBody appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]]; 180 | return httpBody; 181 | } 182 | 183 | - (void)didReceiveMemoryWarning { 184 | [super didReceiveMemoryWarning]; 185 | // Dispose of any resources that can be recreated. 186 | } 187 | 188 | /* 189 | #pragma mark - Navigation 190 | 191 | // In a storyboard-based application, you will often want to do a little preparation before navigation 192 | - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { 193 | // Get the new view controller using [segue destinationViewController]. 194 | // Pass the selected object to the new view controller. 195 | } 196 | */ 197 | 198 | @end 199 | -------------------------------------------------------------------------------- /NMSample/NMSample/Classes/ViewController.h: -------------------------------------------------------------------------------- 1 | // 2 | // ViewController.h 3 | // NetworkMonitorSample 4 | // 5 | // Created by frog78 on 2018/4/23. 6 | // Copyright © 2018年 frog78. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @interface ViewController : UIViewController 12 | 13 | 14 | @end 15 | 16 | -------------------------------------------------------------------------------- /NMSample/NMSample/Classes/ViewController.m: -------------------------------------------------------------------------------- 1 | // 2 | // ViewController.m 3 | // NetworkMonitorSample 4 | // 5 | // Created by frog78 on 2018/4/23. 6 | // Copyright © 2018年 frog78. All rights reserved. 7 | // 8 | 9 | #import "ViewController.h" 10 | #import "NSURLSessionVC.h" 11 | #import "NSURLConnectionVC.h" 12 | #import "AFNetworkingVC.h" 13 | #import "WebViewController.h" 14 | #import 15 | 16 | 17 | @interface ViewController () 18 | 19 | @end 20 | 21 | @implementation ViewController 22 | 23 | - (void)viewDidLoad { 24 | [super viewDidLoad]; 25 | [self initViews]; 26 | } 27 | 28 | - (void)initViews { 29 | self.view.backgroundColor = [UIColor whiteColor]; 30 | self.title = @"网络监控调试"; 31 | UIButton *afnetworking = [[UIButton alloc] initWithFrame:CGRectMake(20, 120, [UIScreen mainScreen].bounds.size.width - 40, 50)]; 32 | [afnetworking setBackgroundColor:[UIColor blueColor]]; 33 | [afnetworking setTitle:@"AFNetworking" forState:UIControlStateNormal]; 34 | [afnetworking addTarget:self action:@selector(afnetworking) forControlEvents:UIControlEventTouchUpInside]; 35 | [self.view addSubview:afnetworking]; 36 | 37 | UIButton *urlconnection = [[UIButton alloc] initWithFrame:CGRectMake(20, 190, [UIScreen mainScreen].bounds.size.width - 40, 50)]; 38 | [urlconnection setBackgroundColor:[UIColor blueColor]]; 39 | [urlconnection setTitle:@"URLConnection" forState:UIControlStateNormal]; 40 | [urlconnection addTarget:self action:@selector(urlconnection) forControlEvents:UIControlEventTouchUpInside]; 41 | [self.view addSubview:urlconnection]; 42 | 43 | UIButton *urlsession = [[UIButton alloc] initWithFrame:CGRectMake(20, 260, [UIScreen mainScreen].bounds.size.width - 40, 50)]; 44 | [urlsession setBackgroundColor:[UIColor blueColor]]; 45 | [urlsession setTitle:@"URLSession" forState:UIControlStateNormal]; 46 | [urlsession addTarget:self action:@selector(urlsession) forControlEvents:UIControlEventTouchUpInside]; 47 | [self.view addSubview:urlsession]; 48 | 49 | UIButton *uiwebview = [[UIButton alloc] initWithFrame:CGRectMake(20, 294, [UIScreen mainScreen].bounds.size.width - 40, 50)]; 50 | [uiwebview setBackgroundColor:[UIColor blueColor]]; 51 | [uiwebview setTitle:@"UIWebView" forState:UIControlStateNormal]; 52 | uiwebview.hidden = YES; 53 | [uiwebview addTarget:self action:@selector(uiwebview) forControlEvents:UIControlEventTouchUpInside]; 54 | [self.view addSubview:uiwebview]; 55 | } 56 | 57 | #pragma mark button-click 58 | - (void)urlsession { 59 | 60 | NSURLSessionVC *sessionVC = [[NSURLSessionVC alloc] init]; 61 | [self.navigationController pushViewController:sessionVC animated:YES]; 62 | } 63 | 64 | - (void)urlconnection { 65 | NSURLConnectionVC *connectionVC = [[NSURLConnectionVC alloc] init]; 66 | [self.navigationController pushViewController:connectionVC animated:YES]; 67 | } 68 | 69 | - (void)afnetworking { 70 | AFNetworkingVC *afnetworkingVC = [[AFNetworkingVC alloc] init]; 71 | [self.navigationController pushViewController:afnetworkingVC animated:YES]; 72 | } 73 | 74 | - (void)uiwebview { 75 | WebViewController *webviewVC = [[WebViewController alloc] init]; 76 | [self.navigationController pushViewController:webviewVC animated:YES]; 77 | } 78 | 79 | 80 | 81 | - (void)didReceiveMemoryWarning { 82 | [super didReceiveMemoryWarning]; 83 | // Dispose of any resources that can be recreated. 84 | } 85 | 86 | 87 | @end 88 | -------------------------------------------------------------------------------- /NMSample/NMSample/Classes/WebViewController.h: -------------------------------------------------------------------------------- 1 | // 2 | // WebViewController.h 3 | // NetworkMonitorSample 4 | // 5 | // Created by frog78 on 2018/5/11. 6 | // Copyright © 2018年 frog78. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @interface WebViewController : UIViewController 12 | 13 | @end 14 | -------------------------------------------------------------------------------- /NMSample/NMSample/Classes/WebViewController.m: -------------------------------------------------------------------------------- 1 | // 2 | // WebViewController.m 3 | // NetworkMonitorSample 4 | // 5 | // Created by frog78 on 2018/5/11. 6 | // Copyright © 2018年 frog78. All rights reserved. 7 | // 8 | 9 | #import "WebViewController.h" 10 | #import 11 | 12 | @interface WebViewController () 13 | 14 | @end 15 | 16 | @implementation WebViewController 17 | 18 | - (void)viewDidLoad { 19 | [super viewDidLoad]; 20 | WKWebView *webview = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)]; 21 | webview.navigationDelegate = self; 22 | NSURL *url = [NSURL URLWithString:@"https://wj.ahga.gov.cn/publicsso/v2?openid.mode=checkid_setup&openid.return_to=https%3A%2F%2Fwj.ahga.gov.cn%2Fbusiness-services%2Fssoclient%3Freturn_url%3D%252Fbusiness-services%252Fh5%252Fremove-car-record&openid.ex.client_id=bg"]; 23 | NSURLRequest *request = [NSURLRequest requestWithURL:url]; 24 | [webview loadRequest:request]; 25 | [self.view addSubview:webview]; 26 | } 27 | 28 | - (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler { 29 | if (navigationAction.targetFrame == nil) { 30 | [webView loadRequest:navigationAction.request]; 31 | } 32 | decisionHandler(WKNavigationActionPolicyAllow); 33 | 34 | } 35 | 36 | - (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler { 37 | decisionHandler(WKNavigationResponsePolicyAllow); 38 | } 39 | 40 | - (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(null_unspecified WKNavigation *)navigation { 41 | 42 | } 43 | 44 | - (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(null_unspecified WKNavigation *)navigation { 45 | 46 | } 47 | 48 | - (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error { 49 | 50 | } 51 | 52 | - (void)webView:(WKWebView *)webView didCommitNavigation:(null_unspecified WKNavigation *)navigation { 53 | 54 | } 55 | 56 | - (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation { 57 | 58 | } 59 | 60 | - (void)webView:(WKWebView *)webView didFailNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error { 61 | 62 | } 63 | 64 | - (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * _Nullable credential))completionHandler { 65 | completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil); 66 | } 67 | 68 | - (void)didReceiveMemoryWarning { 69 | [super didReceiveMemoryWarning]; 70 | // Dispose of any resources that can be recreated. 71 | } 72 | 73 | /* 74 | #pragma mark - Navigation 75 | 76 | // In a storyboard-based application, you will often want to do a little preparation before navigation 77 | - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { 78 | // Get the new view controller using [segue destinationViewController]. 79 | // Pass the selected object to the new view controller. 80 | } 81 | */ 82 | 83 | @end 84 | -------------------------------------------------------------------------------- /NMSample/NMSample/Frameworks/AFNetworking.framework/AFNetworking: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/frog78/NetworkMonitor/f4e13b7485078861b6e90d992f295cc24c952355/NMSample/NMSample/Frameworks/AFNetworking.framework/AFNetworking -------------------------------------------------------------------------------- /NMSample/NMSample/Frameworks/AFNetworking.framework/Headers/AFAutoPurgingImageCache.h: -------------------------------------------------------------------------------- 1 | // AFAutoPurgingImageCache.h 2 | // Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) 3 | // 4 | // Permission is hereby granted, free of charge, to any person obtaining a copy 5 | // of this software and associated documentation files (the "Software"), to deal 6 | // in the Software without restriction, including without limitation the rights 7 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | // copies of the Software, and to permit persons to whom the Software is 9 | // furnished to do so, subject to the following conditions: 10 | // 11 | // The above copyright notice and this permission notice shall be included in 12 | // all copies or substantial portions of the Software. 13 | // 14 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | // THE SOFTWARE. 21 | 22 | #import 23 | #import 24 | 25 | #if TARGET_OS_IOS || TARGET_OS_TV 26 | #import 27 | 28 | NS_ASSUME_NONNULL_BEGIN 29 | 30 | /** 31 | The `AFImageCache` protocol defines a set of APIs for adding, removing and fetching images from a cache synchronously. 32 | */ 33 | @protocol AFImageCache 34 | 35 | /** 36 | Adds the image to the cache with the given identifier. 37 | 38 | @param image The image to cache. 39 | @param identifier The unique identifier for the image in the cache. 40 | */ 41 | - (void)addImage:(UIImage *)image withIdentifier:(NSString *)identifier; 42 | 43 | /** 44 | Removes the image from the cache matching the given identifier. 45 | 46 | @param identifier The unique identifier for the image in the cache. 47 | 48 | @return A BOOL indicating whether or not the image was removed from the cache. 49 | */ 50 | - (BOOL)removeImageWithIdentifier:(NSString *)identifier; 51 | 52 | /** 53 | Removes all images from the cache. 54 | 55 | @return A BOOL indicating whether or not all images were removed from the cache. 56 | */ 57 | - (BOOL)removeAllImages; 58 | 59 | /** 60 | Returns the image in the cache associated with the given identifier. 61 | 62 | @param identifier The unique identifier for the image in the cache. 63 | 64 | @return An image for the matching identifier, or nil. 65 | */ 66 | - (nullable UIImage *)imageWithIdentifier:(NSString *)identifier; 67 | @end 68 | 69 | 70 | /** 71 | The `ImageRequestCache` protocol extends the `ImageCache` protocol by adding methods for adding, removing and fetching images from a cache given an `NSURLRequest` and additional identifier. 72 | */ 73 | @protocol AFImageRequestCache 74 | 75 | /** 76 | Asks if the image should be cached using an identifier created from the request and additional identifier. 77 | 78 | @param image The image to be cached. 79 | @param request The unique URL request identifing the image asset. 80 | @param identifier The additional identifier to apply to the URL request to identify the image. 81 | 82 | @return A BOOL indicating whether or not the image should be added to the cache. YES will cache, NO will prevent caching. 83 | */ 84 | - (BOOL)shouldCacheImage:(UIImage *)image forRequest:(NSURLRequest *)request withAdditionalIdentifier:(nullable NSString *)identifier; 85 | 86 | /** 87 | Adds the image to the cache using an identifier created from the request and additional identifier. 88 | 89 | @param image The image to cache. 90 | @param request The unique URL request identifing the image asset. 91 | @param identifier The additional identifier to apply to the URL request to identify the image. 92 | */ 93 | - (void)addImage:(UIImage *)image forRequest:(NSURLRequest *)request withAdditionalIdentifier:(nullable NSString *)identifier; 94 | 95 | /** 96 | Removes the image from the cache using an identifier created from the request and additional identifier. 97 | 98 | @param request The unique URL request identifing the image asset. 99 | @param identifier The additional identifier to apply to the URL request to identify the image. 100 | 101 | @return A BOOL indicating whether or not all images were removed from the cache. 102 | */ 103 | - (BOOL)removeImageforRequest:(NSURLRequest *)request withAdditionalIdentifier:(nullable NSString *)identifier; 104 | 105 | /** 106 | Returns the image from the cache associated with an identifier created from the request and additional identifier. 107 | 108 | @param request The unique URL request identifing the image asset. 109 | @param identifier The additional identifier to apply to the URL request to identify the image. 110 | 111 | @return An image for the matching request and identifier, or nil. 112 | */ 113 | - (nullable UIImage *)imageforRequest:(NSURLRequest *)request withAdditionalIdentifier:(nullable NSString *)identifier; 114 | 115 | @end 116 | 117 | /** 118 | The `AutoPurgingImageCache` in an in-memory image cache used to store images up to a given memory capacity. When the memory capacity is reached, the image cache is sorted by last access date, then the oldest image is continuously purged until the preferred memory usage after purge is met. Each time an image is accessed through the cache, the internal access date of the image is updated. 119 | */ 120 | @interface AFAutoPurgingImageCache : NSObject 121 | 122 | /** 123 | The total memory capacity of the cache in bytes. 124 | */ 125 | @property (nonatomic, assign) UInt64 memoryCapacity; 126 | 127 | /** 128 | The preferred memory usage after purge in bytes. During a purge, images will be purged until the memory capacity drops below this limit. 129 | */ 130 | @property (nonatomic, assign) UInt64 preferredMemoryUsageAfterPurge; 131 | 132 | /** 133 | The current total memory usage in bytes of all images stored within the cache. 134 | */ 135 | @property (nonatomic, assign, readonly) UInt64 memoryUsage; 136 | 137 | /** 138 | Initialies the `AutoPurgingImageCache` instance with default values for memory capacity and preferred memory usage after purge limit. `memoryCapcity` defaults to `100 MB`. `preferredMemoryUsageAfterPurge` defaults to `60 MB`. 139 | 140 | @return The new `AutoPurgingImageCache` instance. 141 | */ 142 | - (instancetype)init; 143 | 144 | /** 145 | Initialies the `AutoPurgingImageCache` instance with the given memory capacity and preferred memory usage 146 | after purge limit. 147 | 148 | @param memoryCapacity The total memory capacity of the cache in bytes. 149 | @param preferredMemoryCapacity The preferred memory usage after purge in bytes. 150 | 151 | @return The new `AutoPurgingImageCache` instance. 152 | */ 153 | - (instancetype)initWithMemoryCapacity:(UInt64)memoryCapacity preferredMemoryCapacity:(UInt64)preferredMemoryCapacity; 154 | 155 | @end 156 | 157 | NS_ASSUME_NONNULL_END 158 | 159 | #endif 160 | 161 | -------------------------------------------------------------------------------- /NMSample/NMSample/Frameworks/AFNetworking.framework/Headers/AFCompatibilityMacros.h: -------------------------------------------------------------------------------- 1 | // AFCompatibilityMacros.h 2 | // Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) 3 | // 4 | // Permission is hereby granted, free of charge, to any person obtaining a copy 5 | // of this software and associated documentation files (the "Software"), to deal 6 | // in the Software without restriction, including without limitation the rights 7 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | // copies of the Software, and to permit persons to whom the Software is 9 | // furnished to do so, subject to the following conditions: 10 | // 11 | // The above copyright notice and this permission notice shall be included in 12 | // all copies or substantial portions of the Software. 13 | // 14 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | // THE SOFTWARE. 21 | 22 | #ifndef AFCompatibilityMacros_h 23 | #define AFCompatibilityMacros_h 24 | 25 | #ifdef API_UNAVAILABLE 26 | #define AF_API_UNAVAILABLE(x) API_UNAVAILABLE(x) 27 | #else 28 | #define AF_API_UNAVAILABLE(x) 29 | #endif // API_UNAVAILABLE 30 | 31 | #if __has_warning("-Wunguarded-availability-new") 32 | #define AF_CAN_USE_AT_AVAILABLE 1 33 | #else 34 | #define AF_CAN_USE_AT_AVAILABLE 0 35 | #endif 36 | 37 | #endif /* AFCompatibilityMacros_h */ 38 | -------------------------------------------------------------------------------- /NMSample/NMSample/Frameworks/AFNetworking.framework/Headers/AFImageDownloader.h: -------------------------------------------------------------------------------- 1 | // AFImageDownloader.h 2 | // Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) 3 | // 4 | // Permission is hereby granted, free of charge, to any person obtaining a copy 5 | // of this software and associated documentation files (the "Software"), to deal 6 | // in the Software without restriction, including without limitation the rights 7 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | // copies of the Software, and to permit persons to whom the Software is 9 | // furnished to do so, subject to the following conditions: 10 | // 11 | // The above copyright notice and this permission notice shall be included in 12 | // all copies or substantial portions of the Software. 13 | // 14 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | // THE SOFTWARE. 21 | 22 | #import 23 | 24 | #if TARGET_OS_IOS || TARGET_OS_TV 25 | 26 | #import 27 | #import "AFAutoPurgingImageCache.h" 28 | #import "AFHTTPSessionManager.h" 29 | 30 | NS_ASSUME_NONNULL_BEGIN 31 | 32 | typedef NS_ENUM(NSInteger, AFImageDownloadPrioritization) { 33 | AFImageDownloadPrioritizationFIFO, 34 | AFImageDownloadPrioritizationLIFO 35 | }; 36 | 37 | /** 38 | The `AFImageDownloadReceipt` is an object vended by the `AFImageDownloader` when starting a data task. It can be used to cancel active tasks running on the `AFImageDownloader` session. As a general rule, image data tasks should be cancelled using the `AFImageDownloadReceipt` instead of calling `cancel` directly on the `task` itself. The `AFImageDownloader` is optimized to handle duplicate task scenarios as well as pending versus active downloads. 39 | */ 40 | @interface AFImageDownloadReceipt : NSObject 41 | 42 | /** 43 | The data task created by the `AFImageDownloader`. 44 | */ 45 | @property (nonatomic, strong) NSURLSessionDataTask *task; 46 | 47 | /** 48 | The unique identifier for the success and failure blocks when duplicate requests are made. 49 | */ 50 | @property (nonatomic, strong) NSUUID *receiptID; 51 | @end 52 | 53 | /** The `AFImageDownloader` class is responsible for downloading images in parallel on a prioritized queue. Incoming downloads are added to the front or back of the queue depending on the download prioritization. Each downloaded image is cached in the underlying `NSURLCache` as well as the in-memory image cache. By default, any download request with a cached image equivalent in the image cache will automatically be served the cached image representation. 54 | */ 55 | @interface AFImageDownloader : NSObject 56 | 57 | /** 58 | The image cache used to store all downloaded images in. `AFAutoPurgingImageCache` by default. 59 | */ 60 | @property (nonatomic, strong, nullable) id imageCache; 61 | 62 | /** 63 | The `AFHTTPSessionManager` used to download images. By default, this is configured with an `AFImageResponseSerializer`, and a shared `NSURLCache` for all image downloads. 64 | */ 65 | @property (nonatomic, strong) AFHTTPSessionManager *sessionManager; 66 | 67 | /** 68 | Defines the order prioritization of incoming download requests being inserted into the queue. `AFImageDownloadPrioritizationFIFO` by default. 69 | */ 70 | @property (nonatomic, assign) AFImageDownloadPrioritization downloadPrioritizaton; 71 | 72 | /** 73 | The shared default instance of `AFImageDownloader` initialized with default values. 74 | */ 75 | + (instancetype)defaultInstance; 76 | 77 | /** 78 | Creates a default `NSURLCache` with common usage parameter values. 79 | 80 | @returns The default `NSURLCache` instance. 81 | */ 82 | + (NSURLCache *)defaultURLCache; 83 | 84 | /** 85 | The default `NSURLSessionConfiguration` with common usage parameter values. 86 | */ 87 | + (NSURLSessionConfiguration *)defaultURLSessionConfiguration; 88 | 89 | /** 90 | Default initializer 91 | 92 | @return An instance of `AFImageDownloader` initialized with default values. 93 | */ 94 | - (instancetype)init; 95 | 96 | /** 97 | Initializer with specific `URLSessionConfiguration` 98 | 99 | @param configuration The `NSURLSessionConfiguration` to be be used 100 | 101 | @return An instance of `AFImageDownloader` initialized with default values and custom `NSURLSessionConfiguration` 102 | */ 103 | - (instancetype)initWithSessionConfiguration:(NSURLSessionConfiguration *)configuration; 104 | 105 | /** 106 | Initializes the `AFImageDownloader` instance with the given session manager, download prioritization, maximum active download count and image cache. 107 | 108 | @param sessionManager The session manager to use to download images. 109 | @param downloadPrioritization The download prioritization of the download queue. 110 | @param maximumActiveDownloads The maximum number of active downloads allowed at any given time. Recommend `4`. 111 | @param imageCache The image cache used to store all downloaded images in. 112 | 113 | @return The new `AFImageDownloader` instance. 114 | */ 115 | - (instancetype)initWithSessionManager:(AFHTTPSessionManager *)sessionManager 116 | downloadPrioritization:(AFImageDownloadPrioritization)downloadPrioritization 117 | maximumActiveDownloads:(NSInteger)maximumActiveDownloads 118 | imageCache:(nullable id )imageCache; 119 | 120 | /** 121 | Creates a data task using the `sessionManager` instance for the specified URL request. 122 | 123 | If the same data task is already in the queue or currently being downloaded, the success and failure blocks are 124 | appended to the already existing task. Once the task completes, all success or failure blocks attached to the 125 | task are executed in the order they were added. 126 | 127 | @param request The URL request. 128 | @param success A block to be executed when the image data task finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the image created from the response data of request. If the image was returned from cache, the response parameter will be `nil`. 129 | @param failure A block object to be executed when the image data task finishes unsuccessfully, or that finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error object describing the network or parsing error that occurred. 130 | 131 | @return The image download receipt for the data task if available. `nil` if the image is stored in the cache. 132 | cache and the URL request cache policy allows the cache to be used. 133 | */ 134 | - (nullable AFImageDownloadReceipt *)downloadImageForURLRequest:(NSURLRequest *)request 135 | success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *responseObject))success 136 | failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure; 137 | 138 | /** 139 | Creates a data task using the `sessionManager` instance for the specified URL request. 140 | 141 | If the same data task is already in the queue or currently being downloaded, the success and failure blocks are 142 | appended to the already existing task. Once the task completes, all success or failure blocks attached to the 143 | task are executed in the order they were added. 144 | 145 | @param request The URL request. 146 | @param receiptID The identifier to use for the download receipt that will be created for this request. This must be a unique identifier that does not represent any other request. 147 | @param success A block to be executed when the image data task finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the image created from the response data of request. If the image was returned from cache, the response parameter will be `nil`. 148 | @param failure A block object to be executed when the image data task finishes unsuccessfully, or that finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error object describing the network or parsing error that occurred. 149 | 150 | @return The image download receipt for the data task if available. `nil` if the image is stored in the cache. 151 | cache and the URL request cache policy allows the cache to be used. 152 | */ 153 | - (nullable AFImageDownloadReceipt *)downloadImageForURLRequest:(NSURLRequest *)request 154 | withReceiptID:(NSUUID *)receiptID 155 | success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *responseObject))success 156 | failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure; 157 | 158 | /** 159 | Cancels the data task in the receipt by removing the corresponding success and failure blocks and cancelling the data task if necessary. 160 | 161 | If the data task is pending in the queue, it will be cancelled if no other success and failure blocks are registered with the data task. If the data task is currently executing or is already completed, the success and failure blocks are removed and will not be called when the task finishes. 162 | 163 | @param imageDownloadReceipt The image download receipt to cancel. 164 | */ 165 | - (void)cancelTaskForImageDownloadReceipt:(AFImageDownloadReceipt *)imageDownloadReceipt; 166 | 167 | @end 168 | 169 | #endif 170 | 171 | NS_ASSUME_NONNULL_END 172 | -------------------------------------------------------------------------------- /NMSample/NMSample/Frameworks/AFNetworking.framework/Headers/AFNetworkActivityIndicatorManager.h: -------------------------------------------------------------------------------- 1 | // AFNetworkActivityIndicatorManager.h 2 | // Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) 3 | // 4 | // Permission is hereby granted, free of charge, to any person obtaining a copy 5 | // of this software and associated documentation files (the "Software"), to deal 6 | // in the Software without restriction, including without limitation the rights 7 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | // copies of the Software, and to permit persons to whom the Software is 9 | // furnished to do so, subject to the following conditions: 10 | // 11 | // The above copyright notice and this permission notice shall be included in 12 | // all copies or substantial portions of the Software. 13 | // 14 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | // THE SOFTWARE. 21 | 22 | #import 23 | 24 | #import 25 | 26 | #if TARGET_OS_IOS 27 | 28 | #import 29 | 30 | NS_ASSUME_NONNULL_BEGIN 31 | 32 | /** 33 | `AFNetworkActivityIndicatorManager` manages the state of the network activity indicator in the status bar. When enabled, it will listen for notifications indicating that a session task has started or finished, and start or stop animating the indicator accordingly. The number of active requests is incremented and decremented much like a stack or a semaphore, and the activity indicator will animate so long as that number is greater than zero. 34 | 35 | You should enable the shared instance of `AFNetworkActivityIndicatorManager` when your application finishes launching. In `AppDelegate application:didFinishLaunchingWithOptions:` you can do so with the following code: 36 | 37 | [[AFNetworkActivityIndicatorManager sharedManager] setEnabled:YES]; 38 | 39 | By setting `enabled` to `YES` for `sharedManager`, the network activity indicator will show and hide automatically as requests start and finish. You should not ever need to call `incrementActivityCount` or `decrementActivityCount` yourself. 40 | 41 | See the Apple Human Interface Guidelines section about the Network Activity Indicator for more information: 42 | http://developer.apple.com/library/iOS/#documentation/UserExperience/Conceptual/MobileHIG/UIElementGuidelines/UIElementGuidelines.html#//apple_ref/doc/uid/TP40006556-CH13-SW44 43 | */ 44 | NS_EXTENSION_UNAVAILABLE_IOS("Use view controller based solutions where appropriate instead.") 45 | @interface AFNetworkActivityIndicatorManager : NSObject 46 | 47 | /** 48 | A Boolean value indicating whether the manager is enabled. 49 | 50 | If YES, the manager will change status bar network activity indicator according to network operation notifications it receives. The default value is NO. 51 | */ 52 | @property (nonatomic, assign, getter = isEnabled) BOOL enabled; 53 | 54 | /** 55 | A Boolean value indicating whether the network activity indicator manager is currently active. 56 | */ 57 | @property (readonly, nonatomic, assign, getter=isNetworkActivityIndicatorVisible) BOOL networkActivityIndicatorVisible; 58 | 59 | /** 60 | A time interval indicating the minimum duration of networking activity that should occur before the activity indicator is displayed. The default value 1 second. If the network activity indicator should be displayed immediately when network activity occurs, this value should be set to 0 seconds. 61 | 62 | Apple's HIG describes the following: 63 | 64 | > Display the network activity indicator to provide feedback when your app accesses the network for more than a couple of seconds. If the operation finishes sooner than that, you don’t have to show the network activity indicator, because the indicator is likely to disappear before users notice its presence. 65 | 66 | */ 67 | @property (nonatomic, assign) NSTimeInterval activationDelay; 68 | 69 | /** 70 | A time interval indicating the duration of time of no networking activity required before the activity indicator is disabled. This allows for continuous display of the network activity indicator across multiple requests. The default value is 0.17 seconds. 71 | */ 72 | 73 | @property (nonatomic, assign) NSTimeInterval completionDelay; 74 | 75 | /** 76 | Returns the shared network activity indicator manager object for the system. 77 | 78 | @return The systemwide network activity indicator manager. 79 | */ 80 | + (instancetype)sharedManager; 81 | 82 | /** 83 | Increments the number of active network requests. If this number was zero before incrementing, this will start animating the status bar network activity indicator. 84 | */ 85 | - (void)incrementActivityCount; 86 | 87 | /** 88 | Decrements the number of active network requests. If this number becomes zero after decrementing, this will stop animating the status bar network activity indicator. 89 | */ 90 | - (void)decrementActivityCount; 91 | 92 | /** 93 | Set the a custom method to be executed when the network activity indicator manager should be hidden/shown. By default, this is null, and the UIApplication Network Activity Indicator will be managed automatically. If this block is set, it is the responsiblity of the caller to manager the network activity indicator going forward. 94 | 95 | @param block A block to be executed when the network activity indicator status changes. 96 | */ 97 | - (void)setNetworkingActivityActionWithBlock:(nullable void (^)(BOOL networkActivityIndicatorVisible))block; 98 | 99 | @end 100 | 101 | NS_ASSUME_NONNULL_END 102 | 103 | #endif 104 | -------------------------------------------------------------------------------- /NMSample/NMSample/Frameworks/AFNetworking.framework/Headers/AFNetworkReachabilityManager.h: -------------------------------------------------------------------------------- 1 | // AFNetworkReachabilityManager.h 2 | // Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) 3 | // 4 | // Permission is hereby granted, free of charge, to any person obtaining a copy 5 | // of this software and associated documentation files (the "Software"), to deal 6 | // in the Software without restriction, including without limitation the rights 7 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | // copies of the Software, and to permit persons to whom the Software is 9 | // furnished to do so, subject to the following conditions: 10 | // 11 | // The above copyright notice and this permission notice shall be included in 12 | // all copies or substantial portions of the Software. 13 | // 14 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | // THE SOFTWARE. 21 | 22 | #import 23 | 24 | #if !TARGET_OS_WATCH 25 | #import 26 | 27 | typedef NS_ENUM(NSInteger, AFNetworkReachabilityStatus) { 28 | AFNetworkReachabilityStatusUnknown = -1, 29 | AFNetworkReachabilityStatusNotReachable = 0, 30 | AFNetworkReachabilityStatusReachableViaWWAN = 1, 31 | AFNetworkReachabilityStatusReachableViaWiFi = 2, 32 | }; 33 | 34 | NS_ASSUME_NONNULL_BEGIN 35 | 36 | /** 37 | `AFNetworkReachabilityManager` monitors the reachability of domains, and addresses for both WWAN and WiFi network interfaces. 38 | 39 | Reachability can be used to determine background information about why a network operation failed, or to trigger a network operation retrying when a connection is established. It should not be used to prevent a user from initiating a network request, as it's possible that an initial request may be required to establish reachability. 40 | 41 | See Apple's Reachability Sample Code ( https://developer.apple.com/library/ios/samplecode/reachability/ ) 42 | 43 | @warning Instances of `AFNetworkReachabilityManager` must be started with `-startMonitoring` before reachability status can be determined. 44 | */ 45 | @interface AFNetworkReachabilityManager : NSObject 46 | 47 | /** 48 | The current network reachability status. 49 | */ 50 | @property (readonly, nonatomic, assign) AFNetworkReachabilityStatus networkReachabilityStatus; 51 | 52 | /** 53 | Whether or not the network is currently reachable. 54 | */ 55 | @property (readonly, nonatomic, assign, getter = isReachable) BOOL reachable; 56 | 57 | /** 58 | Whether or not the network is currently reachable via WWAN. 59 | */ 60 | @property (readonly, nonatomic, assign, getter = isReachableViaWWAN) BOOL reachableViaWWAN; 61 | 62 | /** 63 | Whether or not the network is currently reachable via WiFi. 64 | */ 65 | @property (readonly, nonatomic, assign, getter = isReachableViaWiFi) BOOL reachableViaWiFi; 66 | 67 | ///--------------------- 68 | /// @name Initialization 69 | ///--------------------- 70 | 71 | /** 72 | Returns the shared network reachability manager. 73 | */ 74 | + (instancetype)sharedManager; 75 | 76 | /** 77 | Creates and returns a network reachability manager with the default socket address. 78 | 79 | @return An initialized network reachability manager, actively monitoring the default socket address. 80 | */ 81 | + (instancetype)manager; 82 | 83 | /** 84 | Creates and returns a network reachability manager for the specified domain. 85 | 86 | @param domain The domain used to evaluate network reachability. 87 | 88 | @return An initialized network reachability manager, actively monitoring the specified domain. 89 | */ 90 | + (instancetype)managerForDomain:(NSString *)domain; 91 | 92 | /** 93 | Creates and returns a network reachability manager for the socket address. 94 | 95 | @param address The socket address (`sockaddr_in6`) used to evaluate network reachability. 96 | 97 | @return An initialized network reachability manager, actively monitoring the specified socket address. 98 | */ 99 | + (instancetype)managerForAddress:(const void *)address; 100 | 101 | /** 102 | Initializes an instance of a network reachability manager from the specified reachability object. 103 | 104 | @param reachability The reachability object to monitor. 105 | 106 | @return An initialized network reachability manager, actively monitoring the specified reachability. 107 | */ 108 | - (instancetype)initWithReachability:(SCNetworkReachabilityRef)reachability NS_DESIGNATED_INITIALIZER; 109 | 110 | /** 111 | * Unavailable initializer 112 | */ 113 | + (instancetype)new NS_UNAVAILABLE; 114 | 115 | /** 116 | * Unavailable initializer 117 | */ 118 | - (instancetype)init NS_UNAVAILABLE; 119 | 120 | ///-------------------------------------------------- 121 | /// @name Starting & Stopping Reachability Monitoring 122 | ///-------------------------------------------------- 123 | 124 | /** 125 | Starts monitoring for changes in network reachability status. 126 | */ 127 | - (void)startMonitoring; 128 | 129 | /** 130 | Stops monitoring for changes in network reachability status. 131 | */ 132 | - (void)stopMonitoring; 133 | 134 | ///------------------------------------------------- 135 | /// @name Getting Localized Reachability Description 136 | ///------------------------------------------------- 137 | 138 | /** 139 | Returns a localized string representation of the current network reachability status. 140 | */ 141 | - (NSString *)localizedNetworkReachabilityStatusString; 142 | 143 | ///--------------------------------------------------- 144 | /// @name Setting Network Reachability Change Callback 145 | ///--------------------------------------------------- 146 | 147 | /** 148 | Sets a callback to be executed when the network availability of the `baseURL` host changes. 149 | 150 | @param block A block object to be executed when the network availability of the `baseURL` host changes.. This block has no return value and takes a single argument which represents the various reachability states from the device to the `baseURL`. 151 | */ 152 | - (void)setReachabilityStatusChangeBlock:(nullable void (^)(AFNetworkReachabilityStatus status))block; 153 | 154 | @end 155 | 156 | ///---------------- 157 | /// @name Constants 158 | ///---------------- 159 | 160 | /** 161 | ## Network Reachability 162 | 163 | The following constants are provided by `AFNetworkReachabilityManager` as possible network reachability statuses. 164 | 165 | enum { 166 | AFNetworkReachabilityStatusUnknown, 167 | AFNetworkReachabilityStatusNotReachable, 168 | AFNetworkReachabilityStatusReachableViaWWAN, 169 | AFNetworkReachabilityStatusReachableViaWiFi, 170 | } 171 | 172 | `AFNetworkReachabilityStatusUnknown` 173 | The `baseURL` host reachability is not known. 174 | 175 | `AFNetworkReachabilityStatusNotReachable` 176 | The `baseURL` host cannot be reached. 177 | 178 | `AFNetworkReachabilityStatusReachableViaWWAN` 179 | The `baseURL` host can be reached via a cellular connection, such as EDGE or GPRS. 180 | 181 | `AFNetworkReachabilityStatusReachableViaWiFi` 182 | The `baseURL` host can be reached via a Wi-Fi connection. 183 | 184 | ### Keys for Notification UserInfo Dictionary 185 | 186 | Strings that are used as keys in a `userInfo` dictionary in a network reachability status change notification. 187 | 188 | `AFNetworkingReachabilityNotificationStatusItem` 189 | A key in the userInfo dictionary in a `AFNetworkingReachabilityDidChangeNotification` notification. 190 | The corresponding value is an `NSNumber` object representing the `AFNetworkReachabilityStatus` value for the current reachability status. 191 | */ 192 | 193 | ///-------------------- 194 | /// @name Notifications 195 | ///-------------------- 196 | 197 | /** 198 | Posted when network reachability changes. 199 | This notification assigns no notification object. The `userInfo` dictionary contains an `NSNumber` object under the `AFNetworkingReachabilityNotificationStatusItem` key, representing the `AFNetworkReachabilityStatus` value for the current network reachability. 200 | 201 | @warning In order for network reachability to be monitored, include the `SystemConfiguration` framework in the active target's "Link Binary With Library" build phase, and add `#import ` to the header prefix of the project (`Prefix.pch`). 202 | */ 203 | FOUNDATION_EXPORT NSString * const AFNetworkingReachabilityDidChangeNotification; 204 | FOUNDATION_EXPORT NSString * const AFNetworkingReachabilityNotificationStatusItem; 205 | 206 | ///-------------------- 207 | /// @name Functions 208 | ///-------------------- 209 | 210 | /** 211 | Returns a localized string representation of an `AFNetworkReachabilityStatus` value. 212 | */ 213 | FOUNDATION_EXPORT NSString * AFStringFromNetworkReachabilityStatus(AFNetworkReachabilityStatus status); 214 | 215 | NS_ASSUME_NONNULL_END 216 | #endif 217 | -------------------------------------------------------------------------------- /NMSample/NMSample/Frameworks/AFNetworking.framework/Headers/AFNetworking.h: -------------------------------------------------------------------------------- 1 | // AFNetworking.h 2 | // Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) 3 | // 4 | // Permission is hereby granted, free of charge, to any person obtaining a copy 5 | // of this software and associated documentation files (the "Software"), to deal 6 | // in the Software without restriction, including without limitation the rights 7 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | // copies of the Software, and to permit persons to whom the Software is 9 | // furnished to do so, subject to the following conditions: 10 | // 11 | // The above copyright notice and this permission notice shall be included in 12 | // all copies or substantial portions of the Software. 13 | // 14 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | // THE SOFTWARE. 21 | 22 | #import 23 | 24 | //! Project version number for AFNetworking. 25 | FOUNDATION_EXPORT double AFNetworkingVersionNumber; 26 | 27 | //! Project version string for AFNetworking. 28 | FOUNDATION_EXPORT const unsigned char AFNetworkingVersionString[]; 29 | 30 | // In this header, you should import all the public headers of your framework using statements like #import 31 | 32 | #import 33 | #import 34 | 35 | #ifndef _AFNETWORKING_ 36 | #define _AFNETWORKING_ 37 | 38 | #import 39 | #import 40 | #import 41 | #import 42 | 43 | #if !TARGET_OS_WATCH 44 | #import 45 | #endif 46 | 47 | #import 48 | #import 49 | 50 | #if TARGET_OS_IOS || TARGET_OS_TV 51 | #import 52 | #import 53 | #import 54 | #import 55 | #import 56 | #import 57 | #import 58 | #endif 59 | 60 | #if TARGET_OS_IOS 61 | #import 62 | #import 63 | #import 64 | #endif 65 | 66 | 67 | #endif /* _AFNETWORKING_ */ 68 | -------------------------------------------------------------------------------- /NMSample/NMSample/Frameworks/AFNetworking.framework/Headers/AFSecurityPolicy.h: -------------------------------------------------------------------------------- 1 | // AFSecurityPolicy.h 2 | // Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) 3 | // 4 | // Permission is hereby granted, free of charge, to any person obtaining a copy 5 | // of this software and associated documentation files (the "Software"), to deal 6 | // in the Software without restriction, including without limitation the rights 7 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | // copies of the Software, and to permit persons to whom the Software is 9 | // furnished to do so, subject to the following conditions: 10 | // 11 | // The above copyright notice and this permission notice shall be included in 12 | // all copies or substantial portions of the Software. 13 | // 14 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | // THE SOFTWARE. 21 | 22 | #import 23 | #import 24 | 25 | typedef NS_ENUM(NSUInteger, AFSSLPinningMode) { 26 | AFSSLPinningModeNone, 27 | AFSSLPinningModePublicKey, 28 | AFSSLPinningModeCertificate, 29 | }; 30 | 31 | /** 32 | `AFSecurityPolicy` evaluates server trust against pinned X.509 certificates and public keys over secure connections. 33 | 34 | Adding pinned SSL certificates to your app helps prevent man-in-the-middle attacks and other vulnerabilities. Applications dealing with sensitive customer data or financial information are strongly encouraged to route all communication over an HTTPS connection with SSL pinning configured and enabled. 35 | */ 36 | 37 | NS_ASSUME_NONNULL_BEGIN 38 | 39 | @interface AFSecurityPolicy : NSObject 40 | 41 | /** 42 | The criteria by which server trust should be evaluated against the pinned SSL certificates. Defaults to `AFSSLPinningModeNone`. 43 | */ 44 | @property (readonly, nonatomic, assign) AFSSLPinningMode SSLPinningMode; 45 | 46 | /** 47 | The certificates used to evaluate server trust according to the SSL pinning mode. 48 | 49 | By default, this property is set to any (`.cer`) certificates included in the target compiling AFNetworking. Note that if you are using AFNetworking as embedded framework, no certificates will be pinned by default. Use `certificatesInBundle` to load certificates from your target, and then create a new policy by calling `policyWithPinningMode:withPinnedCertificates`. 50 | 51 | Note that if pinning is enabled, `evaluateServerTrust:forDomain:` will return true if any pinned certificate matches. 52 | */ 53 | @property (nonatomic, strong, nullable) NSSet *pinnedCertificates; 54 | 55 | /** 56 | Whether or not to trust servers with an invalid or expired SSL certificates. Defaults to `NO`. 57 | */ 58 | @property (nonatomic, assign) BOOL allowInvalidCertificates; 59 | 60 | /** 61 | Whether or not to validate the domain name in the certificate's CN field. Defaults to `YES`. 62 | */ 63 | @property (nonatomic, assign) BOOL validatesDomainName; 64 | 65 | ///----------------------------------------- 66 | /// @name Getting Certificates from the Bundle 67 | ///----------------------------------------- 68 | 69 | /** 70 | Returns any certificates included in the bundle. If you are using AFNetworking as an embedded framework, you must use this method to find the certificates you have included in your app bundle, and use them when creating your security policy by calling `policyWithPinningMode:withPinnedCertificates`. 71 | 72 | @return The certificates included in the given bundle. 73 | */ 74 | + (NSSet *)certificatesInBundle:(NSBundle *)bundle; 75 | 76 | ///----------------------------------------- 77 | /// @name Getting Specific Security Policies 78 | ///----------------------------------------- 79 | 80 | /** 81 | Returns the shared default security policy, which does not allow invalid certificates, validates domain name, and does not validate against pinned certificates or public keys. 82 | 83 | @return The default security policy. 84 | */ 85 | + (instancetype)defaultPolicy; 86 | 87 | ///--------------------- 88 | /// @name Initialization 89 | ///--------------------- 90 | 91 | /** 92 | Creates and returns a security policy with the specified pinning mode. 93 | 94 | @param pinningMode The SSL pinning mode. 95 | 96 | @return A new security policy. 97 | */ 98 | + (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode; 99 | 100 | /** 101 | Creates and returns a security policy with the specified pinning mode. 102 | 103 | @param pinningMode The SSL pinning mode. 104 | @param pinnedCertificates The certificates to pin against. 105 | 106 | @return A new security policy. 107 | */ 108 | + (instancetype)policyWithPinningMode:(AFSSLPinningMode)pinningMode withPinnedCertificates:(NSSet *)pinnedCertificates; 109 | 110 | ///------------------------------ 111 | /// @name Evaluating Server Trust 112 | ///------------------------------ 113 | 114 | /** 115 | Whether or not the specified server trust should be accepted, based on the security policy. 116 | 117 | This method should be used when responding to an authentication challenge from a server. 118 | 119 | @param serverTrust The X.509 certificate trust of the server. 120 | @param domain The domain of serverTrust. If `nil`, the domain will not be validated. 121 | 122 | @return Whether or not to trust the server. 123 | */ 124 | - (BOOL)evaluateServerTrust:(SecTrustRef)serverTrust 125 | forDomain:(nullable NSString *)domain; 126 | 127 | @end 128 | 129 | NS_ASSUME_NONNULL_END 130 | 131 | ///---------------- 132 | /// @name Constants 133 | ///---------------- 134 | 135 | /** 136 | ## SSL Pinning Modes 137 | 138 | The following constants are provided by `AFSSLPinningMode` as possible SSL pinning modes. 139 | 140 | enum { 141 | AFSSLPinningModeNone, 142 | AFSSLPinningModePublicKey, 143 | AFSSLPinningModeCertificate, 144 | } 145 | 146 | `AFSSLPinningModeNone` 147 | Do not used pinned certificates to validate servers. 148 | 149 | `AFSSLPinningModePublicKey` 150 | Validate host certificates against public keys of pinned certificates. 151 | 152 | `AFSSLPinningModeCertificate` 153 | Validate host certificates against pinned certificates. 154 | */ 155 | -------------------------------------------------------------------------------- /NMSample/NMSample/Frameworks/AFNetworking.framework/Headers/UIActivityIndicatorView+AFNetworking.h: -------------------------------------------------------------------------------- 1 | // UIActivityIndicatorView+AFNetworking.h 2 | // Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) 3 | // 4 | // Permission is hereby granted, free of charge, to any person obtaining a copy 5 | // of this software and associated documentation files (the "Software"), to deal 6 | // in the Software without restriction, including without limitation the rights 7 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | // copies of the Software, and to permit persons to whom the Software is 9 | // furnished to do so, subject to the following conditions: 10 | // 11 | // The above copyright notice and this permission notice shall be included in 12 | // all copies or substantial portions of the Software. 13 | // 14 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | // THE SOFTWARE. 21 | 22 | #import 23 | 24 | #import 25 | 26 | #if TARGET_OS_IOS || TARGET_OS_TV 27 | 28 | #import 29 | 30 | /** 31 | This category adds methods to the UIKit framework's `UIActivityIndicatorView` class. The methods in this category provide support for automatically starting and stopping animation depending on the loading state of a session task. 32 | */ 33 | @interface UIActivityIndicatorView (AFNetworking) 34 | 35 | ///---------------------------------- 36 | /// @name Animating for Session Tasks 37 | ///---------------------------------- 38 | 39 | /** 40 | Binds the animating state to the state of the specified task. 41 | 42 | @param task The task. If `nil`, automatic updating from any previously specified operation will be disabled. 43 | */ 44 | - (void)setAnimatingWithStateOfTask:(nullable NSURLSessionTask *)task; 45 | 46 | @end 47 | 48 | #endif 49 | -------------------------------------------------------------------------------- /NMSample/NMSample/Frameworks/AFNetworking.framework/Headers/UIButton+AFNetworking.h: -------------------------------------------------------------------------------- 1 | // UIButton+AFNetworking.h 2 | // Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) 3 | // 4 | // Permission is hereby granted, free of charge, to any person obtaining a copy 5 | // of this software and associated documentation files (the "Software"), to deal 6 | // in the Software without restriction, including without limitation the rights 7 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | // copies of the Software, and to permit persons to whom the Software is 9 | // furnished to do so, subject to the following conditions: 10 | // 11 | // The above copyright notice and this permission notice shall be included in 12 | // all copies or substantial portions of the Software. 13 | // 14 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | // THE SOFTWARE. 21 | 22 | #import 23 | 24 | #import 25 | 26 | #if TARGET_OS_IOS || TARGET_OS_TV 27 | 28 | #import 29 | 30 | NS_ASSUME_NONNULL_BEGIN 31 | 32 | @class AFImageDownloader; 33 | 34 | /** 35 | This category adds methods to the UIKit framework's `UIButton` class. The methods in this category provide support for loading remote images and background images asynchronously from a URL. 36 | 37 | @warning Compound values for control `state` (such as `UIControlStateHighlighted | UIControlStateDisabled`) are unsupported. 38 | */ 39 | @interface UIButton (AFNetworking) 40 | 41 | ///------------------------------------ 42 | /// @name Accessing the Image Downloader 43 | ///------------------------------------ 44 | 45 | /** 46 | Set the shared image downloader used to download images. 47 | 48 | @param imageDownloader The shared image downloader used to download images. 49 | */ 50 | + (void)setSharedImageDownloader:(AFImageDownloader *)imageDownloader; 51 | 52 | /** 53 | The shared image downloader used to download images. 54 | */ 55 | + (AFImageDownloader *)sharedImageDownloader; 56 | 57 | ///-------------------- 58 | /// @name Setting Image 59 | ///-------------------- 60 | 61 | /** 62 | Asynchronously downloads an image from the specified URL, and sets it as the image for the specified state once the request is finished. Any previous image request for the receiver will be cancelled. 63 | 64 | If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished. 65 | 66 | @param state The control state. 67 | @param url The URL used for the image request. 68 | */ 69 | - (void)setImageForState:(UIControlState)state 70 | withURL:(NSURL *)url; 71 | 72 | /** 73 | Asynchronously downloads an image from the specified URL, and sets it as the image for the specified state once the request is finished. Any previous image request for the receiver will be cancelled. 74 | 75 | If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished. 76 | 77 | @param state The control state. 78 | @param url The URL used for the image request. 79 | @param placeholderImage The image to be set initially, until the image request finishes. If `nil`, the button will not change its image until the image request finishes. 80 | */ 81 | - (void)setImageForState:(UIControlState)state 82 | withURL:(NSURL *)url 83 | placeholderImage:(nullable UIImage *)placeholderImage; 84 | 85 | /** 86 | Asynchronously downloads an image from the specified URL request, and sets it as the image for the specified state once the request is finished. Any previous image request for the receiver will be cancelled. 87 | 88 | If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished. 89 | 90 | If a success block is specified, it is the responsibility of the block to set the image of the button before returning. If no success block is specified, the default behavior of setting the image with `setImage:forState:` is applied. 91 | 92 | @param state The control state. 93 | @param urlRequest The URL request used for the image request. 94 | @param placeholderImage The image to be set initially, until the image request finishes. If `nil`, the button will not change its image until the image request finishes. 95 | @param success A block to be executed when the image data task finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the image created from the response data of request. If the image was returned from cache, the response parameter will be `nil`. 96 | @param failure A block object to be executed when the image data task finishes unsuccessfully, or that finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error object describing the network or parsing error that occurred. 97 | */ 98 | - (void)setImageForState:(UIControlState)state 99 | withURLRequest:(NSURLRequest *)urlRequest 100 | placeholderImage:(nullable UIImage *)placeholderImage 101 | success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *image))success 102 | failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure; 103 | 104 | 105 | ///------------------------------- 106 | /// @name Setting Background Image 107 | ///------------------------------- 108 | 109 | /** 110 | Asynchronously downloads an image from the specified URL, and sets it as the background image for the specified state once the request is finished. Any previous background image request for the receiver will be cancelled. 111 | 112 | If the background image is cached locally, the background image is set immediately, otherwise the specified placeholder background image will be set immediately, and then the remote background image will be set once the request is finished. 113 | 114 | @param state The control state. 115 | @param url The URL used for the background image request. 116 | */ 117 | - (void)setBackgroundImageForState:(UIControlState)state 118 | withURL:(NSURL *)url; 119 | 120 | /** 121 | Asynchronously downloads an image from the specified URL, and sets it as the background image for the specified state once the request is finished. Any previous image request for the receiver will be cancelled. 122 | 123 | If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished. 124 | 125 | @param state The control state. 126 | @param url The URL used for the background image request. 127 | @param placeholderImage The background image to be set initially, until the background image request finishes. If `nil`, the button will not change its background image until the background image request finishes. 128 | */ 129 | - (void)setBackgroundImageForState:(UIControlState)state 130 | withURL:(NSURL *)url 131 | placeholderImage:(nullable UIImage *)placeholderImage; 132 | 133 | /** 134 | Asynchronously downloads an image from the specified URL request, and sets it as the image for the specified state once the request is finished. Any previous image request for the receiver will be cancelled. 135 | 136 | If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished. 137 | 138 | If a success block is specified, it is the responsibility of the block to set the image of the button before returning. If no success block is specified, the default behavior of setting the image with `setBackgroundImage:forState:` is applied. 139 | 140 | @param state The control state. 141 | @param urlRequest The URL request used for the image request. 142 | @param placeholderImage The background image to be set initially, until the background image request finishes. If `nil`, the button will not change its background image until the background image request finishes. 143 | @param success A block to be executed when the image data task finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the image created from the response data of request. If the image was returned from cache, the response parameter will be `nil`. 144 | @param failure A block object to be executed when the image data task finishes unsuccessfully, or that finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error object describing the network or parsing error that occurred. 145 | */ 146 | - (void)setBackgroundImageForState:(UIControlState)state 147 | withURLRequest:(NSURLRequest *)urlRequest 148 | placeholderImage:(nullable UIImage *)placeholderImage 149 | success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *image))success 150 | failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure; 151 | 152 | 153 | ///------------------------------ 154 | /// @name Canceling Image Loading 155 | ///------------------------------ 156 | 157 | /** 158 | Cancels any executing image task for the specified control state of the receiver, if one exists. 159 | 160 | @param state The control state. 161 | */ 162 | - (void)cancelImageDownloadTaskForState:(UIControlState)state; 163 | 164 | /** 165 | Cancels any executing background image task for the specified control state of the receiver, if one exists. 166 | 167 | @param state The control state. 168 | */ 169 | - (void)cancelBackgroundImageDownloadTaskForState:(UIControlState)state; 170 | 171 | @end 172 | 173 | NS_ASSUME_NONNULL_END 174 | 175 | #endif 176 | -------------------------------------------------------------------------------- /NMSample/NMSample/Frameworks/AFNetworking.framework/Headers/UIImage+AFNetworking.h: -------------------------------------------------------------------------------- 1 | // 2 | // UIImage+AFNetworking.h 3 | // 4 | // 5 | // Created by Paulo Ferreira on 08/07/15. 6 | // 7 | // Permission is hereby granted, free of charge, to any person obtaining a copy 8 | // of this software and associated documentation files (the "Software"), to deal 9 | // in the Software without restriction, including without limitation the rights 10 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 11 | // copies of the Software, and to permit persons to whom the Software is 12 | // furnished to do so, subject to the following conditions: 13 | // 14 | // The above copyright notice and this permission notice shall be included in 15 | // all copies or substantial portions of the Software. 16 | // 17 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 18 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 19 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 20 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 21 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 22 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 23 | // THE SOFTWARE. 24 | 25 | #if TARGET_OS_IOS || TARGET_OS_TV 26 | 27 | #import 28 | 29 | @interface UIImage (AFNetworking) 30 | 31 | + (UIImage *)safeImageWithData:(NSData *)data; 32 | 33 | @end 34 | 35 | #endif 36 | -------------------------------------------------------------------------------- /NMSample/NMSample/Frameworks/AFNetworking.framework/Headers/UIImageView+AFNetworking.h: -------------------------------------------------------------------------------- 1 | // UIImageView+AFNetworking.h 2 | // Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) 3 | // 4 | // Permission is hereby granted, free of charge, to any person obtaining a copy 5 | // of this software and associated documentation files (the "Software"), to deal 6 | // in the Software without restriction, including without limitation the rights 7 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | // copies of the Software, and to permit persons to whom the Software is 9 | // furnished to do so, subject to the following conditions: 10 | // 11 | // The above copyright notice and this permission notice shall be included in 12 | // all copies or substantial portions of the Software. 13 | // 14 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | // THE SOFTWARE. 21 | 22 | #import 23 | 24 | #import 25 | 26 | #if TARGET_OS_IOS || TARGET_OS_TV 27 | 28 | #import 29 | 30 | NS_ASSUME_NONNULL_BEGIN 31 | 32 | @class AFImageDownloader; 33 | 34 | /** 35 | This category adds methods to the UIKit framework's `UIImageView` class. The methods in this category provide support for loading remote images asynchronously from a URL. 36 | */ 37 | @interface UIImageView (AFNetworking) 38 | 39 | ///------------------------------------ 40 | /// @name Accessing the Image Downloader 41 | ///------------------------------------ 42 | 43 | /** 44 | Set the shared image downloader used to download images. 45 | 46 | @param imageDownloader The shared image downloader used to download images. 47 | */ 48 | + (void)setSharedImageDownloader:(AFImageDownloader *)imageDownloader; 49 | 50 | /** 51 | The shared image downloader used to download images. 52 | */ 53 | + (AFImageDownloader *)sharedImageDownloader; 54 | 55 | ///-------------------- 56 | /// @name Setting Image 57 | ///-------------------- 58 | 59 | /** 60 | Asynchronously downloads an image from the specified URL, and sets it once the request is finished. Any previous image request for the receiver will be cancelled. 61 | 62 | If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished. 63 | 64 | By default, URL requests have a `Accept` header field value of "image / *", a cache policy of `NSURLCacheStorageAllowed` and a timeout interval of 30 seconds, and are set not handle cookies. To configure URL requests differently, use `setImageWithURLRequest:placeholderImage:success:failure:` 65 | 66 | @param url The URL used for the image request. 67 | */ 68 | - (void)setImageWithURL:(NSURL *)url; 69 | 70 | /** 71 | Asynchronously downloads an image from the specified URL, and sets it once the request is finished. Any previous image request for the receiver will be cancelled. 72 | 73 | If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished. 74 | 75 | By default, URL requests have a `Accept` header field value of "image / *", a cache policy of `NSURLCacheStorageAllowed` and a timeout interval of 30 seconds, and are set not handle cookies. To configure URL requests differently, use `setImageWithURLRequest:placeholderImage:success:failure:` 76 | 77 | @param url The URL used for the image request. 78 | @param placeholderImage The image to be set initially, until the image request finishes. If `nil`, the image view will not change its image until the image request finishes. 79 | */ 80 | - (void)setImageWithURL:(NSURL *)url 81 | placeholderImage:(nullable UIImage *)placeholderImage; 82 | 83 | /** 84 | Asynchronously downloads an image from the specified URL request, and sets it once the request is finished. Any previous image request for the receiver will be cancelled. 85 | 86 | If the image is cached locally, the image is set immediately, otherwise the specified placeholder image will be set immediately, and then the remote image will be set once the request is finished. 87 | 88 | If a success block is specified, it is the responsibility of the block to set the image of the image view before returning. If no success block is specified, the default behavior of setting the image with `self.image = image` is applied. 89 | 90 | @param urlRequest The URL request used for the image request. 91 | @param placeholderImage The image to be set initially, until the image request finishes. If `nil`, the image view will not change its image until the image request finishes. 92 | @param success A block to be executed when the image data task finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the image created from the response data of request. If the image was returned from cache, the response parameter will be `nil`. 93 | @param failure A block object to be executed when the image data task finishes unsuccessfully, or that finishes successfully. This block has no return value and takes three arguments: the request sent from the client, the response received from the server, and the error object describing the network or parsing error that occurred. 94 | */ 95 | - (void)setImageWithURLRequest:(NSURLRequest *)urlRequest 96 | placeholderImage:(nullable UIImage *)placeholderImage 97 | success:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, UIImage *image))success 98 | failure:(nullable void (^)(NSURLRequest *request, NSHTTPURLResponse * _Nullable response, NSError *error))failure; 99 | 100 | /** 101 | Cancels any executing image operation for the receiver, if one exists. 102 | */ 103 | - (void)cancelImageDownloadTask; 104 | 105 | @end 106 | 107 | NS_ASSUME_NONNULL_END 108 | 109 | #endif 110 | -------------------------------------------------------------------------------- /NMSample/NMSample/Frameworks/AFNetworking.framework/Headers/UIProgressView+AFNetworking.h: -------------------------------------------------------------------------------- 1 | // UIProgressView+AFNetworking.h 2 | // Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) 3 | // 4 | // Permission is hereby granted, free of charge, to any person obtaining a copy 5 | // of this software and associated documentation files (the "Software"), to deal 6 | // in the Software without restriction, including without limitation the rights 7 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | // copies of the Software, and to permit persons to whom the Software is 9 | // furnished to do so, subject to the following conditions: 10 | // 11 | // The above copyright notice and this permission notice shall be included in 12 | // all copies or substantial portions of the Software. 13 | // 14 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | // THE SOFTWARE. 21 | 22 | #import 23 | 24 | #import 25 | 26 | #if TARGET_OS_IOS || TARGET_OS_TV 27 | 28 | #import 29 | 30 | NS_ASSUME_NONNULL_BEGIN 31 | 32 | 33 | /** 34 | This category adds methods to the UIKit framework's `UIProgressView` class. The methods in this category provide support for binding the progress to the upload and download progress of a session task. 35 | */ 36 | @interface UIProgressView (AFNetworking) 37 | 38 | ///------------------------------------ 39 | /// @name Setting Session Task Progress 40 | ///------------------------------------ 41 | 42 | /** 43 | Binds the progress to the upload progress of the specified session task. 44 | 45 | @param task The session task. 46 | @param animated `YES` if the change should be animated, `NO` if the change should happen immediately. 47 | */ 48 | - (void)setProgressWithUploadProgressOfTask:(NSURLSessionUploadTask *)task 49 | animated:(BOOL)animated; 50 | 51 | /** 52 | Binds the progress to the download progress of the specified session task. 53 | 54 | @param task The session task. 55 | @param animated `YES` if the change should be animated, `NO` if the change should happen immediately. 56 | */ 57 | - (void)setProgressWithDownloadProgressOfTask:(NSURLSessionDownloadTask *)task 58 | animated:(BOOL)animated; 59 | 60 | @end 61 | 62 | NS_ASSUME_NONNULL_END 63 | 64 | #endif 65 | -------------------------------------------------------------------------------- /NMSample/NMSample/Frameworks/AFNetworking.framework/Headers/UIRefreshControl+AFNetworking.h: -------------------------------------------------------------------------------- 1 | // UIRefreshControl+AFNetworking.m 2 | // 3 | // Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) 4 | // 5 | // Permission is hereby granted, free of charge, to any person obtaining a copy 6 | // of this software and associated documentation files (the "Software"), to deal 7 | // in the Software without restriction, including without limitation the rights 8 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | // copies of the Software, and to permit persons to whom the Software is 10 | // furnished to do so, subject to the following conditions: 11 | // 12 | // The above copyright notice and this permission notice shall be included in 13 | // all copies or substantial portions of the Software. 14 | // 15 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 | // THE SOFTWARE. 22 | 23 | #import 24 | 25 | #import 26 | 27 | #if TARGET_OS_IOS 28 | 29 | #import 30 | 31 | NS_ASSUME_NONNULL_BEGIN 32 | 33 | /** 34 | This category adds methods to the UIKit framework's `UIRefreshControl` class. The methods in this category provide support for automatically beginning and ending refreshing depending on the loading state of a session task. 35 | */ 36 | @interface UIRefreshControl (AFNetworking) 37 | 38 | ///----------------------------------- 39 | /// @name Refreshing for Session Tasks 40 | ///----------------------------------- 41 | 42 | /** 43 | Binds the refreshing state to the state of the specified task. 44 | 45 | @param task The task. If `nil`, automatic updating from any previously specified operation will be disabled. 46 | */ 47 | - (void)setRefreshingWithStateOfTask:(NSURLSessionTask *)task; 48 | 49 | @end 50 | 51 | NS_ASSUME_NONNULL_END 52 | 53 | #endif 54 | -------------------------------------------------------------------------------- /NMSample/NMSample/Frameworks/AFNetworking.framework/Headers/UIWebView+AFNetworking.h: -------------------------------------------------------------------------------- 1 | // UIWebView+AFNetworking.h 2 | // Copyright (c) 2011–2016 Alamofire Software Foundation ( http://alamofire.org/ ) 3 | // 4 | // Permission is hereby granted, free of charge, to any person obtaining a copy 5 | // of this software and associated documentation files (the "Software"), to deal 6 | // in the Software without restriction, including without limitation the rights 7 | // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 8 | // copies of the Software, and to permit persons to whom the Software is 9 | // furnished to do so, subject to the following conditions: 10 | // 11 | // The above copyright notice and this permission notice shall be included in 12 | // all copies or substantial portions of the Software. 13 | // 14 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 15 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 16 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 17 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 18 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 19 | // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 20 | // THE SOFTWARE. 21 | 22 | #import 23 | 24 | #import 25 | 26 | #if TARGET_OS_IOS 27 | 28 | #import 29 | 30 | NS_ASSUME_NONNULL_BEGIN 31 | 32 | @class AFHTTPSessionManager; 33 | 34 | /** 35 | This category adds methods to the UIKit framework's `UIWebView` class. The methods in this category provide increased control over the request cycle, including progress monitoring and success / failure handling. 36 | 37 | @discussion When using these category methods, make sure to assign `delegate` for the web view, which implements `–webView:shouldStartLoadWithRequest:navigationType:` appropriately. This allows for tapped links to be loaded through AFNetworking, and can ensure that `canGoBack` & `canGoForward` update their values correctly. 38 | */ 39 | @interface UIWebView (AFNetworking) 40 | 41 | /** 42 | The session manager used to download all requests. 43 | */ 44 | @property (nonatomic, strong) AFHTTPSessionManager *sessionManager; 45 | 46 | /** 47 | Asynchronously loads the specified request. 48 | 49 | @param request A URL request identifying the location of the content to load. This must not be `nil`. 50 | @param progress A progress object monitoring the current download progress. 51 | @param success A block object to be executed when the request finishes loading successfully. This block returns the HTML string to be loaded by the web view, and takes two arguments: the response, and the response string. 52 | @param failure A block object to be executed when the data task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a single argument: the error that occurred. 53 | */ 54 | - (void)loadRequest:(NSURLRequest *)request 55 | progress:(NSProgress * _Nullable __autoreleasing * _Nullable)progress 56 | success:(nullable NSString * (^)(NSHTTPURLResponse *response, NSString *HTML))success 57 | failure:(nullable void (^)(NSError *error))failure; 58 | 59 | /** 60 | Asynchronously loads the data associated with a particular request with a specified MIME type and text encoding. 61 | 62 | @param request A URL request identifying the location of the content to load. This must not be `nil`. 63 | @param MIMEType The MIME type of the content. Defaults to the content type of the response if not specified. 64 | @param textEncodingName The IANA encoding name, as in `utf-8` or `utf-16`. Defaults to the response text encoding if not specified. 65 | @param progress A progress object monitoring the current download progress. 66 | @param success A block object to be executed when the request finishes loading successfully. This block returns the data to be loaded by the web view and takes two arguments: the response, and the downloaded data. 67 | @param failure A block object to be executed when the data task finishes unsuccessfully, or that finishes successfully, but encountered an error while parsing the response data. This block has no return value and takes a single argument: the error that occurred. 68 | */ 69 | - (void)loadRequest:(NSURLRequest *)request 70 | MIMEType:(nullable NSString *)MIMEType 71 | textEncodingName:(nullable NSString *)textEncodingName 72 | progress:(NSProgress * _Nullable __autoreleasing * _Nullable)progress 73 | success:(nullable NSData * (^)(NSHTTPURLResponse *response, NSData *data))success 74 | failure:(nullable void (^)(NSError *error))failure; 75 | 76 | @end 77 | 78 | NS_ASSUME_NONNULL_END 79 | 80 | #endif 81 | -------------------------------------------------------------------------------- /NMSample/NMSample/Frameworks/AFNetworking.framework/Info.plist: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/frog78/NetworkMonitor/f4e13b7485078861b6e90d992f295cc24c952355/NMSample/NMSample/Frameworks/AFNetworking.framework/Info.plist -------------------------------------------------------------------------------- /NMSample/NMSample/Frameworks/AFNetworking.framework/Modules/module.modulemap: -------------------------------------------------------------------------------- 1 | framework module AFNetworking { 2 | umbrella header "AFNetworking.h" 3 | export * 4 | module * { export * } 5 | } -------------------------------------------------------------------------------- /NMSample/NMSample/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | $(DEVELOPMENT_LANGUAGE) 7 | CFBundleExecutable 8 | $(EXECUTABLE_NAME) 9 | CFBundleIdentifier 10 | $(PRODUCT_BUNDLE_IDENTIFIER) 11 | CFBundleInfoDictionaryVersion 12 | 6.0 13 | CFBundleName 14 | $(PRODUCT_NAME) 15 | CFBundlePackageType 16 | APPL 17 | CFBundleShortVersionString 18 | $(MARKETING_VERSION) 19 | CFBundleVersion 20 | 1 21 | LSRequiresIPhoneOS 22 | 23 | NSAppTransportSecurity 24 | 25 | NSAllowsArbitraryLoads 26 | 27 | 28 | UILaunchStoryboardName 29 | LaunchScreen 30 | UIMainStoryboardFile 31 | Main 32 | UIRequiredDeviceCapabilities 33 | 34 | armv7 35 | 36 | UISupportedInterfaceOrientations 37 | 38 | UIInterfaceOrientationPortrait 39 | UIInterfaceOrientationLandscapeLeft 40 | UIInterfaceOrientationLandscapeRight 41 | 42 | UISupportedInterfaceOrientations~ipad 43 | 44 | UIInterfaceOrientationPortrait 45 | UIInterfaceOrientationPortraitUpsideDown 46 | UIInterfaceOrientationLandscapeLeft 47 | UIInterfaceOrientationLandscapeRight 48 | 49 | 50 | 51 | -------------------------------------------------------------------------------- /NMSample/NMSample/main.m: -------------------------------------------------------------------------------- 1 | // 2 | // main.m 3 | // NMSample 4 | // 5 | // Created by frog78 on 2018/8/16. 6 | // Copyright © 2018年 frog78. All rights reserved. 7 | // 8 | 9 | #import 10 | #import "AppDelegate.h" 11 | 12 | int main(int argc, char * argv[]) { 13 | @autoreleasepool { 14 | return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class])); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /NMSample/NMSampleTests/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | $(DEVELOPMENT_LANGUAGE) 7 | CFBundleExecutable 8 | $(EXECUTABLE_NAME) 9 | CFBundleIdentifier 10 | $(PRODUCT_BUNDLE_IDENTIFIER) 11 | CFBundleInfoDictionaryVersion 12 | 6.0 13 | CFBundleName 14 | $(PRODUCT_NAME) 15 | CFBundlePackageType 16 | BNDL 17 | CFBundleShortVersionString 18 | 1.0 19 | CFBundleVersion 20 | 1 21 | 22 | 23 | -------------------------------------------------------------------------------- /NMSample/NMSampleTests/NMSampleTests.m: -------------------------------------------------------------------------------- 1 | // 2 | // NMSampleTests.m 3 | // NMSampleTests 4 | // 5 | // Created by frog78 on 2018/8/16. 6 | // Copyright © 2018年 frog78. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @interface NMSampleTests : XCTestCase 12 | 13 | @end 14 | 15 | @implementation NMSampleTests 16 | 17 | - (void)setUp { 18 | [super setUp]; 19 | // Put setup code here. This method is called before the invocation of each test method in the class. 20 | } 21 | 22 | - (void)tearDown { 23 | // Put teardown code here. This method is called after the invocation of each test method in the class. 24 | [super tearDown]; 25 | } 26 | 27 | - (void)testExample { 28 | // This is an example of a functional test case. 29 | // Use XCTAssert and related functions to verify your tests produce the correct results. 30 | } 31 | 32 | - (void)testPerformanceExample { 33 | // This is an example of a performance test case. 34 | [self measureBlock:^{ 35 | // Put the code you want to measure the time of here. 36 | }]; 37 | } 38 | 39 | @end 40 | -------------------------------------------------------------------------------- /NetworkMonitor.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /NetworkMonitor.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | IDEDidComputeMac32BitWarning 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /NetworkMonitor/NetworkMonitor.xcodeproj/project.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /NetworkMonitor/NetworkMonitor.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | IDEDidComputeMac32BitWarning 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /NetworkMonitor/NetworkMonitor/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | $(DEVELOPMENT_LANGUAGE) 7 | CFBundleExecutable 8 | $(EXECUTABLE_NAME) 9 | CFBundleIdentifier 10 | $(PRODUCT_BUNDLE_IDENTIFIER) 11 | CFBundleInfoDictionaryVersion 12 | 6.0 13 | CFBundleName 14 | $(PRODUCT_NAME) 15 | CFBundlePackageType 16 | FMWK 17 | CFBundleShortVersionString 18 | $(MARKETING_VERSION) 19 | CFBundleVersion 20 | $(CURRENT_PROJECT_VERSION) 21 | NSPrincipalClass 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /NetworkMonitor/NetworkMonitor/NMAOP/NMHooker.h: -------------------------------------------------------------------------------- 1 | // 2 | // NMHooker.h 3 | // NetworkMonitor 4 | // 5 | // Created by frog78 on 2018/4/24. 6 | // Copyright © 2018年 frog78. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | /** 12 | 通过Runtime交换类、实例方法 13 | */ 14 | @interface NMHooker : NSObject 15 | 16 | /** 17 | hook实例方法 18 | 19 | @param oriClass 原实例类名 20 | @param oriSel 原实例方法名 21 | @param newClass 新的实例类名 22 | @param newSel 新的实例方法名 23 | */ 24 | + (void)hookInstance:(NSString *)oriClass sel:(NSString *)oriSel withClass:(NSString *)newClass andSel:(NSString *)newSel; 25 | 26 | /** 27 | hook类方法 28 | 29 | @param oriClass 原类名 30 | @param oriSel 原类方法名 31 | @param newClass 新的类名 32 | @param newSel 新的类方法名 33 | */ 34 | + (void)hookClass:(NSString *)oriClass sel:(NSString *)oriSel withClass:(NSString *)newClass andSel:(NSString *)newSel; 35 | 36 | 37 | @end 38 | -------------------------------------------------------------------------------- /NetworkMonitor/NetworkMonitor/NMAOP/NMHooker.m: -------------------------------------------------------------------------------- 1 | // 2 | // NMHooker.m 3 | // NetworkMonitor 4 | // 5 | // Created by frog78 on 2018/4/24. 6 | // Copyright © 2018年 frog78. All rights reserved. 7 | // 8 | 9 | #import "NMHooker.h" 10 | #import 11 | 12 | @implementation NMHooker 13 | 14 | + (void)hookInstance:(NSString *)oriClass sel:(NSString *)oriSel withClass:(NSString *)newClass andSel:(NSString *)newSel { 15 | Class hookedClass = objc_getClass([oriClass UTF8String]); 16 | Class swizzledClass = objc_getClass([newClass UTF8String]); 17 | #pragma clang diagnostic push 18 | #pragma clang diagnostic ignored "-Wundeclared-selector" 19 | SEL oriSelector = NSSelectorFromString(oriSel); 20 | SEL swizzledSelector = NSSelectorFromString(newSel); 21 | #pragma clang diagnostic pop 22 | Method originalMethod = class_getInstanceMethod(hookedClass, oriSelector); 23 | Method swizzledMethod = class_getInstanceMethod(swizzledClass, swizzledSelector); 24 | method_exchangeImplementations(originalMethod, swizzledMethod); 25 | } 26 | 27 | 28 | + (void)hookClass:(NSString *)oriClass sel:(NSString *)oriSel withClass:(NSString *)newClass andSel:(NSString *)newSel { 29 | Class hookedClass = objc_getClass([oriClass UTF8String]); 30 | Class swizzledClass = objc_getClass([newClass UTF8String]); 31 | #pragma clang diagnostic push 32 | #pragma clang diagnostic ignored "-Wundeclared-selector" 33 | SEL oriSelector = NSSelectorFromString(oriSel); 34 | SEL swizzledSelector = NSSelectorFromString(newSel); 35 | #pragma clang diagnostic pop 36 | Method originalMethod = class_getClassMethod(hookedClass, oriSelector); 37 | Method swizzledMethod = class_getClassMethod(swizzledClass, swizzledSelector); 38 | method_exchangeImplementations(originalMethod, swizzledMethod); 39 | } 40 | 41 | 42 | @end 43 | -------------------------------------------------------------------------------- /NetworkMonitor/NetworkMonitor/NMAOP/NMObjectDelegate.h: -------------------------------------------------------------------------------- 1 | // 2 | // NMObjectDelegate.h 3 | // NetworkMonitor 4 | // 5 | // Created by frog78 on 2018/4/26. 6 | // Copyright © 2018年 frog78. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | /** 12 | @class NMObjectDelegate 13 | @abstract 当应用层没有设置实现NSURLSessionDelegate或者NSURLConnectionDelegate的代理时,NetworkMonitor会将本类的一个实例设置为代理,代理方法将被转发到本类的实现。 14 | */ 15 | @interface NMObjectDelegate : NSObject 16 | 17 | /** 18 | 代理方法调用传递 19 | 20 | @param invocation 方法调用对象 21 | */ 22 | - (void)invoke:(NSInvocation *)invocation; 23 | 24 | /** 25 | 注册需要调用传递的方法 26 | 27 | @param selector 方法名 28 | */ 29 | - (void)registerSelector:(NSString *)selector; 30 | 31 | /** 32 | 注销需要调用传递的方法 33 | 34 | @param selector 方法名 35 | */ 36 | - (void)unregisterSelector:(NSString *)selector; 37 | 38 | 39 | 40 | @end 41 | -------------------------------------------------------------------------------- /NetworkMonitor/NetworkMonitor/NMAOP/NMProxy.h: -------------------------------------------------------------------------------- 1 | // 2 | // NMProxy.h 3 | // NetworkMonitor 4 | // 5 | // Created by frog78 on 2018/4/24. 6 | // Copyright © 2018年 frog78. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @class NMObjectDelegate; 12 | 13 | /** 14 | 代理方法监控类,注册对象的代理后,代理方法的调用会 15 | 流经该类的几个特定方法。 16 | */ 17 | @interface NMProxy : NSProxy 18 | 19 | /** 20 | 注册对象代理 21 | 22 | @param obj 需要注册的代理 23 | @param delegate 代理方法 24 | @return 返回包裹了代理监控的代理对象 25 | */ 26 | + (id)proxyForObject:(id)obj delegate:(NMObjectDelegate *)delegate; 27 | 28 | 29 | @end 30 | -------------------------------------------------------------------------------- /NetworkMonitor/NetworkMonitor/NMAOP/NMProxy.m: -------------------------------------------------------------------------------- 1 | // 2 | // NMProxy.m 3 | // NetworkMonitor 4 | // 5 | // Created by frog78 on 2018/4/24. 6 | // Copyright © 2018年 frog78. All rights reserved. 7 | // 8 | 9 | #import "NMProxy.h" 10 | #import "NMObjectDelegate.h" 11 | 12 | @interface NMProxy() { 13 | id _object; //代理对象 14 | NMObjectDelegate *_objectDelegate; //代理方法调用传递对象 15 | } 16 | 17 | @end 18 | 19 | @implementation NMProxy 20 | 21 | + (id)proxyForObject:(id)obj delegate:(NMObjectDelegate *)delegate { 22 | NMProxy *instance = [NMProxy alloc]; 23 | instance->_object = obj; 24 | instance->_objectDelegate = delegate; 25 | 26 | return instance; 27 | } 28 | 29 | - (NSMethodSignature *)methodSignatureForSelector:(SEL)sel { 30 | return [_object methodSignatureForSelector:sel]; 31 | } 32 | 33 | - (void)forwardInvocation:(NSInvocation *)invocation { 34 | if ([_object respondsToSelector:invocation.selector]) { 35 | //代理方法执行 36 | [invocation invokeWithTarget:_object]; 37 | //代理方法执行传递 38 | [_objectDelegate invoke:invocation]; 39 | } 40 | } 41 | 42 | 43 | @end 44 | -------------------------------------------------------------------------------- /NetworkMonitor/NetworkMonitor/NMAOP/NMURLProtocol.h: -------------------------------------------------------------------------------- 1 | // 2 | // NMURLProtocol.h 3 | // NetworkMonitor 4 | // 5 | // Created by frog78 on 2018/4/24. 6 | // Copyright © 2018年 frog78. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @interface NMURLProtocol : NSURLProtocol 12 | 13 | @end 14 | -------------------------------------------------------------------------------- /NetworkMonitor/NetworkMonitor/NMAOP/NMURLProtocol.m: -------------------------------------------------------------------------------- 1 | // 2 | // NMURLProtocol.m 3 | // NetworkMonitor 4 | // 5 | // Created by frog78 on 2018/4/24. 6 | // Copyright © 2018年 frog78. All rights reserved. 7 | // 8 | 9 | #import "NMURLProtocol.h" 10 | 11 | @implementation NMURLProtocol 12 | 13 | + (void)load { 14 | // [NSURLProtocol registerClass:[self class]]; 15 | } 16 | 17 | + (BOOL)canInitWithRequest:(NSURLRequest *)request { 18 | NSURL *url = [request URL]; 19 | EELog(@"%@", url) 20 | return NO; 21 | } 22 | 23 | + (NSURLRequest*)canonicalRequestForRequest:(NSURLRequest *)request { 24 | return request; 25 | } 26 | 27 | 28 | - (void)startLoading { 29 | NSLog(@"startLoading"); 30 | } 31 | 32 | - (void)stopLoading { 33 | NSLog(@"stopLoading"); 34 | } 35 | 36 | //- (void)responseData:(NSData *)data withHeaders:(NSMutableDictionary *)headers { 37 | // NSURLResponse *response = [[NSHTTPURLResponse alloc] initWithURL:[[self request] URL] statusCode:200 HTTPVersion:@"HTTP/1.1" headerFields:headers]; 38 | // [[self client] URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed]; 39 | // [[self client] URLProtocol:self didLoadData:data]; 40 | // [[self client] URLProtocolDidFinishLoading:self]; 41 | //} 42 | // 43 | //- (void)response404 { 44 | // NSMutableDictionary* headers = [[NSMutableDictionary alloc] init]; 45 | // headers[@"Cache-Control"] = @"no-cache"; 46 | // NSURLResponse *response = [[NSHTTPURLResponse alloc] initWithURL:[[self request] URL] statusCode:404 HTTPVersion:@"HTTP/1.1" headerFields:headers]; 47 | // [[self client] URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed]; 48 | // [[self client] URLProtocolDidFinishLoading:self]; 49 | //} 50 | 51 | 52 | - (NSCachedURLResponse *)connection:(NSURLConnection *)connection willCacheResponse:(NSCachedURLResponse *)cachedResponse { 53 | return nil; 54 | } 55 | 56 | 57 | 58 | 59 | @end 60 | -------------------------------------------------------------------------------- /NetworkMonitor/NetworkMonitor/NMAOP/NSHTTPURLResponse+NM.h: -------------------------------------------------------------------------------- 1 | // 2 | // NSHTTPURLResponse+NM.h 3 | // NetworkMonitor 4 | // 5 | // Created by frog78 on 2018/5/15. 6 | // Copyright © 2018年 frog78. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | /** 12 | 为响应头添加traceId 13 | */ 14 | @interface NSHTTPURLResponse (EE) 15 | 16 | /** 17 | 在响应头中添加traceId 18 | */ 19 | @property (nonatomic, strong) NSString *traceId; 20 | 21 | @property (nonatomic, assign, readonly) NSUInteger statusLineSize; 22 | 23 | @property (nonatomic, assign, readonly) NSUInteger headerSize; 24 | 25 | @end 26 | -------------------------------------------------------------------------------- /NetworkMonitor/NetworkMonitor/NMAOP/NSHTTPURLResponse+NM.m: -------------------------------------------------------------------------------- 1 | // 2 | // NSHTTPURLResponse+NM.m 3 | // NetworkMonitor 4 | // 5 | // Created by frog78 on 2018/5/15. 6 | // Copyright © 2018年 frog78. All rights reserved. 7 | // 8 | 9 | #import "NSHTTPURLResponse+NM.h" 10 | #import "NMHooker.h" 11 | #import 12 | #import 13 | 14 | typedef CFHTTPMessageRef (*NMResponseGetHTTPResponse)(CFURLRef response); 15 | 16 | static char *NSHTTPURLResponseEEKey = "NSHTTPURLResponseEEKey"; 17 | 18 | @implementation NSHTTPURLResponse (EE) 19 | 20 | + (void)load { 21 | [NMHooker hookInstance:@"NSHTTPURLResponse" sel:@"allHeaderFields" withClass:@"NSHTTPURLResponse" andSel:@"hook_allHeaderFields"]; 22 | } 23 | 24 | - (NSDictionary *)hook_allHeaderFields { 25 | NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:[self hook_allHeaderFields]]; 26 | if (self.traceId) { 27 | [dic setObject:self.traceId forKey:HEAD_KEY_EETRACEID]; 28 | } 29 | return dic; 30 | } 31 | 32 | - (void)setTraceId:(NSString *)traceId { 33 | objc_setAssociatedObject(self, NSHTTPURLResponseEEKey, traceId, OBJC_ASSOCIATION_RETAIN_NONATOMIC); 34 | } 35 | 36 | - (NSString *)traceId { 37 | return objc_getAssociatedObject(self, NSHTTPURLResponseEEKey); 38 | } 39 | 40 | - (NSUInteger)statusLineSize { 41 | NSURLResponse *response = self; 42 | NSString *statusLine = @""; 43 | // 获取CFURLResponseGetHTTPResponse的函数实现 44 | NSString *funName = @"CFURLResponseGetHTTPResponse"; 45 | NMResponseGetHTTPResponse originURLResponseGetHTTPResponse = 46 | dlsym(RTLD_DEFAULT, [funName UTF8String]); 47 | SEL theSelector = NSSelectorFromString(@"_CFURLResponse"); 48 | if ([response respondsToSelector:theSelector] && 49 | NULL != originURLResponseGetHTTPResponse) { 50 | // 获取NSURLResponse的_CFURLResponse 51 | CFTypeRef cfResponse = CFBridgingRetain([response performSelector:theSelector]); 52 | if (NULL != cfResponse) { 53 | // 将CFURLResponseRef转化为CFHTTPMessageRef 54 | CFHTTPMessageRef messageRef = originURLResponseGetHTTPResponse(cfResponse); 55 | statusLine = (__bridge_transfer NSString *)CFHTTPMessageCopyResponseStatusLine(messageRef); 56 | CFRelease(cfResponse); 57 | } 58 | } 59 | NSData *lineData = [statusLine dataUsingEncoding:NSUTF8StringEncoding]; 60 | return lineData.length; 61 | } 62 | 63 | - (NSUInteger)headerSize { 64 | NSUInteger headersLength = 0; 65 | if ([self isKindOfClass:[NSHTTPURLResponse class]]) { 66 | NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)self; 67 | NSDictionary *headerFields = httpResponse.allHeaderFields; 68 | NSString *headerStr = @""; 69 | for (NSString *key in headerFields.allKeys) { 70 | headerStr = [headerStr stringByAppendingString:key]; 71 | headerStr = [headerStr stringByAppendingString:@": "]; 72 | if ([headerFields objectForKey:key]) { 73 | headerStr = [headerStr stringByAppendingString:headerFields[key]]; 74 | } 75 | headerStr = [headerStr stringByAppendingString:@"\n"]; 76 | } 77 | NSData *headerData = [headerStr dataUsingEncoding:NSUTF8StringEncoding]; 78 | headersLength = headerData.length; 79 | } 80 | return headersLength; 81 | } 82 | 83 | 84 | @end 85 | -------------------------------------------------------------------------------- /NetworkMonitor/NetworkMonitor/NMAOP/NSURLConnection+NM.h: -------------------------------------------------------------------------------- 1 | // 2 | // NSURLConnection+NM.h 3 | // NetworkMonitor 4 | // 5 | // Created by frog78 on 2018/4/28. 6 | // Copyright © 2018年 frog78. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | 12 | /** 13 | NSURLConnection扩展,用于NSURLConnection相关方法的监控 14 | */ 15 | @interface NSURLConnection (NM) 16 | 17 | /** 18 | hook NSURLConnection 相关方法 19 | */ 20 | + (void)hook; 21 | 22 | /** 23 | 取消hook NSURLConnection 相关方法 24 | */ 25 | //+ (void)unhook; 26 | 27 | 28 | @end 29 | -------------------------------------------------------------------------------- /NetworkMonitor/NetworkMonitor/NMAOP/NSURLRequest+NM.h: -------------------------------------------------------------------------------- 1 | // 2 | // NSURLRequest+NM.h 3 | // NetworkMonitor 4 | // 5 | // Created by frog78 on 2018/6/6. 6 | // Copyright © 2018年 frog78. All rights reserved. 7 | // 8 | 9 | #import 10 | #import "NSData+GZIP.h" 11 | 12 | @interface NSURLRequest (EE) 13 | 14 | @property (nonatomic, assign, readonly) NSUInteger statusLineSize; 15 | 16 | @property (nonatomic, assign, readonly) NSUInteger headerSize; 17 | 18 | @property (nonatomic, assign, readonly) NSUInteger bodySize; 19 | 20 | @end 21 | -------------------------------------------------------------------------------- /NetworkMonitor/NetworkMonitor/NMAOP/NSURLRequest+NM.m: -------------------------------------------------------------------------------- 1 | // 2 | // NSURLRequest+NM.m 3 | // NetworkMonitor 4 | // 5 | // Created by frog78 on 2018/6/6. 6 | // Copyright © 2018年 frog78. All rights reserved. 7 | // 8 | 9 | #import "NSURLRequest+NM.h" 10 | 11 | @implementation NSURLRequest (EE) 12 | 13 | - (NSUInteger)statusLineSize { 14 | NSString *lineStr = [NSString stringWithFormat:@"%@ %@ %@\n", self.HTTPMethod, self.URL.path, @"HTTP/1.1"]; 15 | NSData *lineData = [lineStr dataUsingEncoding:NSUTF8StringEncoding]; 16 | return lineData.length; 17 | } 18 | 19 | - (NSUInteger)headerSize { 20 | NSUInteger headersLength = 0; 21 | 22 | NSDictionary *headerFields = self.allHTTPHeaderFields; 23 | NSDictionary *cookiesHeader = [self dgm_getCookies]; 24 | 25 | // 添加 cookie 信息 26 | if (cookiesHeader.count) { 27 | NSMutableDictionary *headerFieldsWithCookies = [NSMutableDictionary dictionaryWithDictionary:headerFields]; 28 | [headerFieldsWithCookies addEntriesFromDictionary:cookiesHeader]; 29 | headerFields = [headerFieldsWithCookies copy]; 30 | } 31 | NSString *headerStr = @""; 32 | for (NSString *key in headerFields.allKeys) { 33 | headerStr = [headerStr stringByAppendingString:key]; 34 | headerStr = [headerStr stringByAppendingString:@": "]; 35 | if ([headerFields objectForKey:key]) { 36 | headerStr = [headerStr stringByAppendingString:headerFields[key]]; 37 | } 38 | headerStr = [headerStr stringByAppendingString:@"\n"]; 39 | } 40 | NSData *headerData = [headerStr dataUsingEncoding:NSUTF8StringEncoding]; 41 | headersLength = headerData.length; 42 | //一般header中字段会比统计到的多,+180作为数据补充 43 | return headersLength + 180; 44 | } 45 | 46 | - (NSDictionary *)dgm_getCookies { 47 | NSDictionary *cookiesHeader; 48 | if (!self.URL) { 49 | return nil; 50 | } 51 | NSHTTPCookieStorage *cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage]; 52 | NSArray *cookies = [cookieStorage cookiesForURL:self.URL]; 53 | if (cookies.count) { 54 | cookiesHeader = [NSHTTPCookie requestHeaderFieldsWithCookies:cookies]; 55 | } 56 | return cookiesHeader; 57 | } 58 | 59 | - (NSUInteger)bodySize { 60 | NSDictionary *headerFields = self.allHTTPHeaderFields; 61 | NSUInteger bodyLength = [self.HTTPBody length]; 62 | 63 | if ([headerFields objectForKey:@"Content-Encoding"]) { 64 | NSData *bodyData; 65 | if (self.HTTPBody == nil) { 66 | uint8_t d[1024] = {0}; 67 | NSInputStream *stream = self.HTTPBodyStream; 68 | NSMutableData *data = [[NSMutableData alloc] init]; 69 | [stream open]; 70 | while ([stream hasBytesAvailable]) { 71 | NSInteger len = [stream read:d maxLength:1024]; 72 | if (len > 0 && stream.streamError == nil) { 73 | [data appendBytes:(void *)d length:len]; 74 | } 75 | } 76 | bodyData = [data copy]; 77 | [stream close]; 78 | } else { 79 | bodyData = self.HTTPBody; 80 | } 81 | bodyLength = [[bodyData gzippedData] length]; 82 | } 83 | return bodyLength; 84 | } 85 | 86 | 87 | @end 88 | -------------------------------------------------------------------------------- /NetworkMonitor/NetworkMonitor/NMAOP/NSURLSession+NM.h: -------------------------------------------------------------------------------- 1 | // 2 | // NSURLSession+NM.h 3 | // NetworkMonitor 4 | // 5 | // Created by frog78 on 2018/4/25. 6 | // Copyright © 2018年 frog78. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | 12 | /** 13 | NSURLSession扩展,用于NSURLSession相关方法的监控 14 | */ 15 | @interface NSURLSession (EE) 16 | 17 | /** 18 | hook NSURLSession 相关方法 19 | */ 20 | + (void)hook; 21 | 22 | /** 23 | 取消hook NSURLSession 相关方法 24 | */ 25 | //+ (void)unhook; 26 | 27 | 28 | @end 29 | -------------------------------------------------------------------------------- /NetworkMonitor/NetworkMonitor/NMCache/NMCache.h: -------------------------------------------------------------------------------- 1 | // 2 | // NMCache.h 3 | // NetworkMonitor 4 | // 5 | // Created by frog78 on 2018/4/24. 6 | // Copyright © 2018年 frog78. All rights reserved. 7 | // 8 | 9 | #import 10 | #import "NMModelCommon.h" 11 | 12 | extern NSString *NMDATA_KEY_EXTENSION; 13 | extern NSString *NMDATA_KEY_TRACEID; 14 | extern NSString *NMDATA_KEY_ERRORCODE; 15 | //extern NSString *NMDATA_KEY_STATUSCODE; 16 | extern NSString *NMDATA_KEY_STATE; 17 | extern NSString *NMDATA_KEY_REQUESTSIZE; 18 | extern NSString *NMDATA_KEY_REDIRECTIP; 19 | extern NSString *NMDATA_KEY_ORIGINALIP; 20 | extern NSString *NMDATA_KEY_REDIRECTURL; 21 | extern NSString *NMDATA_KEY_ORIGINALURL; 22 | extern NSString *NMDATA_KEY_APN; 23 | extern NSString *NMDATA_KEY_NETSTRENGTH; 24 | extern NSString *NMDATA_KEY_TOTALTIME; 25 | extern NSString *NMDATA_KEY_ENDRESPONSE; 26 | extern NSString *NMDATA_KEY_RECEIVETIME; 27 | extern NSString *NMDATA_KEY_WAITTIME; 28 | extern NSString *NMDATA_KEY_SENDTIME; 29 | extern NSString *NMDATA_KEY_CONNTIME; 30 | extern NSString *NMDATA_KEY_SSLTIME; 31 | extern NSString *NMDATA_KEY_DNSTIME; 32 | extern NSString *NMDATA_KEY_STARTREQUEST; 33 | extern NSString *NMDATA_KEY_CONTENTTYPE; 34 | extern NSString *NMDATA_KEY_RESPONSESIZE; 35 | extern NSString *NMDATA_KEY_ERRORDETAIL; 36 | 37 | extern NSString *NMDATA_KEY_REQUESTSIZE_HEAD; 38 | extern NSString *NMDATA_KEY_REQUESTSIZE_BODY; 39 | 40 | typedef NS_ENUM(NSInteger, CacheDataType) { 41 | CacheDataTypeDownload = 0, 42 | CacheDataTypeUpload, 43 | CacheDataTypeOther 44 | }; 45 | 46 | @interface NMCache : NSObject 47 | 48 | + (instancetype)sharedNMCache; 49 | 50 | /** 51 | 根据traceId暂时缓存键值对 52 | 53 | @param value 值 54 | @param key 键 55 | @param traceId 单次网络请求唯一id 56 | */ 57 | - (void)cacheValue:(NSString *)value key:(const NSString *)key traceId:(NSString *)traceId; 58 | 59 | /** 60 | 根据traceId暂时缓存扩展参数 61 | 62 | @param ext 扩展参数字典 63 | @param traceId 网络请求唯一id 64 | @return 返回值 1表示同一条traceId数据还没持久化,0表示已经持久化 65 | */ 66 | - (int)cacheExtension:(NSDictionary *)ext traceId:(NSString *)traceId; 67 | 68 | /** 69 | 根据traceId持久化网络请求数据 70 | 71 | @param traceId 网络请求唯一id 72 | */ 73 | - (void)persistData:(NSString *)traceId; 74 | 75 | /** 76 | 获取全部数据 77 | 78 | @return 返回数据 79 | */ 80 | - (id)getAllData; 81 | 82 | /** 83 | 删除全部数据 84 | */ 85 | - (void)removeAllData; 86 | 87 | #pragma mark-临时数据缓存 88 | /** 89 | 通过traceId储存数据 90 | 91 | @param data 数据片段 92 | @param traceId 唯一记录Id 93 | */ 94 | - (void)appendData:(NSData *)data byTraceId:(NSString *)traceId; 95 | 96 | /** 97 | 通过traceId删除储存数据 98 | 99 | @param traceId 唯一记录Id 100 | */ 101 | - (void)removeDataByTraceId:(NSString *)traceId; 102 | 103 | /** 104 | 通过traceId获取到 105 | 106 | @param traceId 唯一记录Id 107 | @return 返回数据值 108 | */ 109 | - (NSData *)getDataByTraceId:(NSString *)traceId; 110 | 111 | /** 112 | 通过traceId储存已下载数据大小 113 | 114 | @param num 要储存的数据 115 | @param traceId 唯一记录Id 116 | */ 117 | - (void)cacheNum:(NSNumber *)num byTraceId:(NSString *)traceId 118 | type:(CacheDataType)type; 119 | 120 | /** 121 | 通过traceId删除储存数据 122 | 123 | @param traceId 唯一记录Id 124 | */ 125 | - (void)removeNumByTraceId:(NSString *)traceId type:(CacheDataType)type; 126 | 127 | /** 128 | 通过traceId获取到 129 | 130 | @param traceId 唯一记录Id 131 | @return 返回数据值 132 | */ 133 | - (NSNumber *)getNumByTraceId:(NSString *)traceId type:(CacheDataType)type; 134 | 135 | 136 | @end 137 | -------------------------------------------------------------------------------- /NetworkMonitor/NetworkMonitor/NMCache/NMCache.m: -------------------------------------------------------------------------------- 1 | // 2 | // NMCache.m 3 | // NetworkMonitor 4 | // 5 | // Created by frog78 on 2018/4/24. 6 | // Copyright © 2018年 frog78. All rights reserved. 7 | // 8 | 9 | #import "NMCache.h" 10 | #import "NMDataModel.h" 11 | #import "NMDataDAO.h" 12 | 13 | //对外暴露字段名 14 | const NSString *NMDATA_KEY_CMD = @"cmd"; 15 | const NSString *NMDATA_KEY_ERRORTYPE = @"etp"; 16 | const NSString *NMDATA_KEY_RESPONSEDATA = @"ddata"; 17 | const NSString *NMDATA_KEY_ORIGINALMD5 = @"omd5"; 18 | const NSString *NMDATA_KEY_DOWNLOADMD5 = @"dmd5"; 19 | const NSString *NMDATA_KEY_ORIGINALSIZE = @"osize"; 20 | const NSString *NMDATA_KEY_DOWNLOADSIZE = @"dsize"; 21 | const NSString *NMDATA_KEY_REALDOWNLOADSIZE = @"rdsize"; 22 | 23 | //非对外暴露字段名 24 | const NSString *NMDATA_KEY_EXTENSION = @"extension"; 25 | const NSString *NMDATA_KEY_TRACEID = @"ti"; 26 | const NSString *NMDATA_KEY_ERRORCODE = @"ec"; 27 | //const NSString *NMDATA_KEY_STATUSCODE = @"sc"; 28 | const NSString *NMDATA_KEY_STATE = @"state"; 29 | const NSString *NMDATA_KEY_REQUESTSIZE = @"reqs"; 30 | const NSString *NMDATA_KEY_REDIRECTIP = @"rip"; 31 | const NSString *NMDATA_KEY_ORIGINALIP = @"oip"; 32 | const NSString *NMDATA_KEY_REDIRECTURL = @"rurl"; 33 | const NSString *NMDATA_KEY_ORIGINALURL = @"ourl"; 34 | const NSString *NMDATA_KEY_APN = @"apn"; 35 | const NSString *NMDATA_KEY_NETSTRENGTH = @"ns"; 36 | const NSString *NMDATA_KEY_TOTALTIME = @"ttt"; 37 | const NSString *NMDATA_KEY_ENDRESPONSE = @"eres"; 38 | const NSString *NMDATA_KEY_RECEIVETIME = @"rcvt"; 39 | const NSString *NMDATA_KEY_WAITTIME = @"wtt"; 40 | const NSString *NMDATA_KEY_SENDTIME = @"sdt"; 41 | const NSString *NMDATA_KEY_CONNTIME = @"cnnt"; 42 | const NSString *NMDATA_KEY_SSLTIME = @"sslt"; 43 | const NSString *NMDATA_KEY_DNSTIME = @"dnst"; 44 | const NSString *NMDATA_KEY_STARTREQUEST = @"sreq"; 45 | const NSString *NMDATA_KEY_CONTENTTYPE = @"cty"; 46 | const NSString *NMDATA_KEY_RESPONSESIZE = @"ress"; 47 | const NSString *NMDATA_KEY_ERRORDETAIL = @"ed"; 48 | 49 | const NSString *NMDATA_KEY_REQUESTSIZE_HEAD = @"reqs_head"; 50 | const NSString *NMDATA_KEY_REQUESTSIZE_BODY = @"reqs_body"; 51 | 52 | @interface NMCache() 53 | 54 | @property (nonatomic, strong)NSMutableDictionary *cache; 55 | @property (nonatomic, strong)NSMutableDictionary *dataCache; 56 | @property (nonatomic, strong)NSMutableDictionary *downloadCache; 57 | @property (nonatomic, strong)NSMutableDictionary *uploadCache; 58 | @property (nonatomic, strong)NMDataDAO *dao; 59 | 60 | @end 61 | 62 | @implementation NMCache 63 | 64 | 65 | + (instancetype)sharedNMCache { 66 | static NMCache *nmCache = nil; 67 | static dispatch_once_t onceToken; 68 | dispatch_once(&onceToken, ^{ 69 | if (!nmCache) { 70 | nmCache = [[NMCache alloc] init]; 71 | } 72 | }); 73 | return nmCache; 74 | } 75 | 76 | - (void)cacheValue:(NSString *)value key:(NSString *)key traceId:(NSString *)traceId { 77 | if (!value || !key || !traceId) { 78 | return; 79 | } 80 | @synchronized (self) { 81 | NMDataModel *model = self.cache[traceId]; 82 | if (!model) { 83 | model = [[NMDataModel alloc] init]; 84 | model.ti = traceId; 85 | model.ns = [NMUtil getNetWorkInfo]; 86 | model.apn = [NMUtil getDetailApCode]; 87 | [self.cache setObject:model forKey:traceId]; 88 | } 89 | if ([key isEqualToString:(NSString *)NMDATA_KEY_REQUESTSIZE_HEAD]) { 90 | [model setRequestHeaderSize:value]; 91 | } else if ([key isEqualToString:(NSString *)NMDATA_KEY_REQUESTSIZE_BODY]) { 92 | [model setRequestBodySize:value]; 93 | } else { 94 | [model setValue:value forKey:key]; 95 | } 96 | } 97 | } 98 | 99 | - (int)cacheExtension:(NSDictionary *)ext traceId:(NSString *)traceId { 100 | if (!ext || !traceId) { 101 | return 1; 102 | } 103 | @synchronized (self) { 104 | NMDataModel *model = self.cache[traceId]; 105 | int tag = 1; 106 | if (!model) { 107 | tag = 0; 108 | model = [[NMDataModel alloc] init]; 109 | model.ti = traceId; 110 | model.ns = [NMUtil getNetWorkInfo]; 111 | model.apn = [NMUtil getDetailApCode]; 112 | [self.cache setObject:model forKey:traceId]; 113 | } 114 | if (model.extension) { 115 | NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:model.extension]; 116 | [dic addEntriesFromDictionary:ext]; 117 | model.extension = dic; 118 | } else { 119 | model.extension = ext; 120 | } 121 | return tag; 122 | } 123 | } 124 | 125 | - (void)persistData:(NSString *)traceId { 126 | if (!traceId) { 127 | return; 128 | } 129 | NMDataModel *model = self.cache[traceId]; 130 | if (!model.ttt && model.sreq && model.eres) { 131 | model.ttt = [NSString stringWithFormat:@"%lld", [model.eres longLongValue] - [model.sreq longLongValue]]; 132 | } 133 | //判断是否为NSURLConnection delegate记录的时间点 134 | // if ([model.wtt longLongValue] > 10000) { 135 | // model.rcvt = [NSString stringWithFormat:@"%lld", [model.eres longLongValue] - [model.wtt longLongValue]]; 136 | // model.wtt = [NSString stringWithFormat:@"%lld", [model.wtt longLongValue] - [model.sreq longLongValue]]; 137 | // } 138 | //如果设置了block,则直接通过block回调 139 | if ([NMManager sharedNMManager].outputBlock) { 140 | dispatch_async(dispatch_get_main_queue(), ^{ 141 | [NMManager sharedNMManager].outputBlock(traceId, [model toDictionary]); 142 | EELog(@"%@", [model toDictionary]); 143 | [self.cache removeObjectForKey:traceId]; 144 | }); 145 | return; 146 | } 147 | 148 | @synchronized (self) { 149 | dispatch_async(dispatch_get_main_queue(), ^{ 150 | if ([self.dao insertOrModify:model] == 0) { 151 | [self.cache removeObjectForKey:traceId]; 152 | EELog(@"%@", [model toDictionary]); 153 | } 154 | }); 155 | } 156 | } 157 | 158 | - (id)getAllData { 159 | return [self.dao findAll]; 160 | } 161 | 162 | - (void)removeAllData { 163 | [self.dao removeAll]; 164 | } 165 | 166 | - (NSMutableDictionary *)cache { 167 | if (!_cache) { 168 | _cache = [NSMutableDictionary dictionaryWithCapacity:0]; 169 | } 170 | return _cache; 171 | } 172 | 173 | - (NMDataDAO *)dao { 174 | if (!_dao) { 175 | _dao = [NMDataDAO share]; 176 | } 177 | return _dao; 178 | } 179 | 180 | - (void)appendData:(NSData *)data byTraceId:(NSString *)traceId { 181 | if (!traceId) { 182 | return; 183 | } 184 | NSMutableData *oriData = self.dataCache[traceId]; 185 | if (oriData) { 186 | [oriData appendData:data]; 187 | } else { 188 | [self.dataCache setValue:[NSMutableData dataWithData:data] forKey:traceId]; 189 | } 190 | } 191 | 192 | - (void)removeDataByTraceId:(NSString *)traceId { 193 | if (traceId) { 194 | [self.dataCache removeObjectForKey:traceId]; 195 | } 196 | } 197 | 198 | - (NSData *)getDataByTraceId:(NSString *)traceId { 199 | return self.dataCache[traceId]; 200 | } 201 | 202 | - (NSMutableDictionary *)dataCache { 203 | if (!_dataCache) { 204 | _dataCache = [NSMutableDictionary dictionaryWithCapacity:0]; 205 | } 206 | return _dataCache; 207 | } 208 | 209 | - (void)cacheNum:(NSNumber *)num byTraceId:(NSString *)traceId type:(CacheDataType)type { 210 | if (!traceId) { 211 | return; 212 | } 213 | if (type == CacheDataTypeUpload) { 214 | [self.uploadCache setValue:num forKey:traceId]; 215 | } else if (type == CacheDataTypeDownload) { 216 | [self.downloadCache setValue:num forKey:traceId]; 217 | } else { 218 | } 219 | } 220 | 221 | - (void)removeNumByTraceId:(NSString *)traceId type:(CacheDataType)type { 222 | if (!traceId) { 223 | return; 224 | } 225 | if (type == CacheDataTypeUpload) { 226 | [self.uploadCache removeObjectForKey:traceId]; 227 | } else if (type == CacheDataTypeDownload) { 228 | [self.downloadCache removeObjectForKey:traceId]; 229 | } else { 230 | } 231 | } 232 | 233 | - (NSNumber *)getNumByTraceId:(NSString *)traceId type:(CacheDataType)type { 234 | if (type == CacheDataTypeUpload) { 235 | return self.uploadCache[traceId]; 236 | } else if (type == CacheDataTypeDownload) { 237 | return self.downloadCache[traceId]; 238 | } else { 239 | return nil; 240 | } 241 | } 242 | 243 | - (NSMutableDictionary *)downloadCache { 244 | if (!_downloadCache) { 245 | _downloadCache = [NSMutableDictionary dictionaryWithCapacity:0]; 246 | } 247 | return _downloadCache; 248 | } 249 | 250 | - (NSMutableDictionary *)uploadCache { 251 | if (!_uploadCache) { 252 | _uploadCache = [NSMutableDictionary dictionaryWithCapacity:0]; 253 | } 254 | return _uploadCache; 255 | } 256 | 257 | @end 258 | -------------------------------------------------------------------------------- /NetworkMonitor/NetworkMonitor/NMCache/NMDataModel.h: -------------------------------------------------------------------------------- 1 | // 2 | // NMDATAModel.h 3 | // NetworkMonitor 4 | // 5 | // Created by frog78 on 2018/4/24. 6 | // Copyright © 2018年 frog78. All rights reserved. 7 | // 8 | 9 | #import 10 | #import "NMModelCommon.h" 11 | 12 | /** 13 | 端到端监控缓存数据模型 14 | */ 15 | @interface NMDataModel : NMModelCommon 16 | 17 | 18 | /** 19 | 单次请求的唯一id.(=ti) 20 | */ 21 | @property (strong, nonatomic) NSString *ti; 22 | 23 | /** 24 | 当前接入点名称(wifi、cmwap、ctwap、uniwap、cmnet、uninet、ctnet、g3net、g3wap、unknown).(=apn) 25 | */ 26 | @property (strong, nonatomic) NSString *apn; 27 | 28 | /** 29 | 网络类型(=networktype) 30 | */ 31 | @property (strong, nonatomic) NSString *ns; 32 | 33 | // 接口描述.(=cmd) 34 | @property (strong, nonatomic) NSString *cmd; 35 | 36 | /** 37 | 原始url.(=originalUrl) 38 | */ 39 | @property (strong, nonatomic) NSString *ourl; 40 | 41 | /** 42 | 重定向url.(=redirectUrl) 43 | */ 44 | @property (strong, nonatomic) NSString *rurl; 45 | 46 | /** 47 | 原始ip.(=originalIp) 48 | */ 49 | @property (strong, nonatomic) NSString *oip; 50 | 51 | /** 52 | 重定向ip.(=redirectIp) 53 | */ 54 | @property (strong, nonatomic) NSString *rip; 55 | 56 | /** 57 | 请求包大小.(=requestSize) 58 | */ 59 | @property (strong, nonatomic) NSString *reqs; 60 | 61 | /** 62 | 接口请求结果:success、failure、cancel.(=state) 63 | */ 64 | @property (strong, nonatomic) NSString *state; 65 | 66 | /** 67 | 状态码(=statusCode) 68 | */ 69 | @property (strong, nonatomic) NSString *sc; 70 | 71 | /** 72 | 错误类型:1网络错误 2http错误 3业务错误.(=errorType) 73 | */ 74 | @property (strong, nonatomic) NSString *etp; 75 | 76 | /** 77 | 错误码.(=errorCode) 78 | */ 79 | @property (strong, nonatomic) NSString *ec; 80 | 81 | /** 82 | 错误描述.(=errorDetail) 83 | */ 84 | @property (strong, nonatomic) NSString *ed; 85 | 86 | /** 87 | 返回包大小.(=responseSize) 88 | */ 89 | @property (strong, nonatomic) NSString *ress; 90 | 91 | /** 92 | mimeType.(=contentType) 93 | */ 94 | @property (strong, nonatomic) NSString *cty; 95 | 96 | /** 97 | 返回包(状态为失败时记录).(=responseData) 98 | */ 99 | @property (strong, nonatomic) NSString *ddata; 100 | 101 | /** 102 | 请求开始时间.(=startRequest) 103 | */ 104 | @property (strong, nonatomic) NSString *sreq; 105 | 106 | /** 107 | 域名解析的时间.(=dnsTime) 108 | */ 109 | @property (strong, nonatomic) NSString *dnst; 110 | 111 | /** 112 | SSL的时间,仅针对https,当http时此项为空.(=sslTime) 113 | */ 114 | @property (strong, nonatomic) NSString *sslt; 115 | 116 | /** 117 | 与服务器建立tcp链接需要的时间.(=connTime) 118 | */ 119 | @property (strong, nonatomic) NSString *cnnt; 120 | 121 | /** 122 | 从客户端发送HTTP请求到服务器所耗费的时间.(=sendTime) 123 | */ 124 | @property (strong, nonatomic) NSString *sdt; 125 | 126 | /** 127 | 响应报文首字节到达时间.(=waitTime) 128 | */ 129 | @property (strong, nonatomic) NSString *wtt; 130 | 131 | /** 132 | 客户端从开始接收数据到接收完所有数据的时间.(=receiveTime) 133 | */ 134 | @property (strong, nonatomic) NSString *rcvt; 135 | 136 | /** 137 | 响应结束时间.(=endResponse) 138 | */ 139 | @property (strong, nonatomic) NSString *eres; 140 | 141 | /** 142 | 请求总耗时.(=totalTime) 143 | */ 144 | @property (strong, nonatomic) NSString *ttt; 145 | 146 | /** 147 | 原始md5信息.(=originalMd5) 148 | */ 149 | @property (strong, nonatomic) NSString *omd5; 150 | 151 | /** 152 | 下载成功文件的md5信息.(=downloadMd5) 153 | */ 154 | @property (strong, nonatomic) NSString *dmd5; 155 | 156 | /** 157 | 原始文件大小,单位:字节.(=originalSize) 158 | */ 159 | @property (strong, nonatomic) NSString *osize; 160 | 161 | /** 162 | 下载成功文件的文件大小,单位:字节.(=downloadSize) 163 | */ 164 | @property (strong, nonatomic) NSString *dsize; 165 | 166 | /** 167 | 实际下载大小(md5不一致时记录),单位:字节.(=realDownloadSize) 168 | */ 169 | @property (strong, nonatomic) NSString *rdsize; 170 | 171 | /** 172 | 扩展数据 173 | */ 174 | @property (strong, nonatomic) NSDictionary *extension; 175 | 176 | - (void)setRequestHeaderSize:(NSString *)size; 177 | 178 | - (void)setRequestBodySize:(NSString *)size; 179 | 180 | 181 | @end 182 | -------------------------------------------------------------------------------- /NetworkMonitor/NetworkMonitor/NMCache/NMDataModel.m: -------------------------------------------------------------------------------- 1 | // 2 | // NMDATAModel.m 3 | // NetworkMonitor 4 | // 5 | // Created by frog78 on 2018/4/24. 6 | // Copyright © 2018年 frog78. All rights reserved. 7 | // 8 | 9 | #import "NMDataModel.h" 10 | 11 | @interface NMDataModel() { 12 | NSString * _headerSize; 13 | NSString * _bodySize; 14 | } 15 | 16 | @end 17 | 18 | @implementation NMDataModel 19 | 20 | - (void)setCnnt:(NSString *)cnnt { 21 | if (!_cnnt) { 22 | _cnnt = cnnt; 23 | } 24 | } 25 | 26 | - (void)setSreq:(NSString *)sreq { 27 | if (!_sreq) { 28 | _sreq = sreq; 29 | } 30 | } 31 | 32 | - (void)setDnst:(NSString *)dnst { 33 | if (!_dnst) { 34 | _dnst = dnst; 35 | } 36 | } 37 | 38 | - (void)setSslt:(NSString *)sslt { 39 | if (!_sslt) { 40 | _sslt = sslt; 41 | } 42 | } 43 | 44 | - (void)setSdt:(NSString *)sdt { 45 | if (!_sdt) { 46 | _sdt = sdt; 47 | } 48 | } 49 | 50 | - (void)setWtt:(NSString *)wtt { 51 | if (!_wtt) { 52 | _wtt = wtt; 53 | } 54 | } 55 | 56 | - (void)setRcvt:(NSString *)rcvt { 57 | if (!_rcvt) { 58 | _rcvt = rcvt; 59 | } 60 | } 61 | 62 | - (void)setEres:(NSString *)eres { 63 | if (!_eres) { 64 | _eres = eres; 65 | } 66 | } 67 | 68 | - (void)setTtt:(NSString *)ttt { 69 | if (!_ttt) { 70 | _ttt = ttt; 71 | } 72 | } 73 | 74 | - (void)setOurl:(NSString *)ourl { 75 | if (!_ourl) { 76 | _ourl = ourl; 77 | } 78 | } 79 | 80 | - (void)setOip:(NSString *)oip { 81 | if (!_oip) { 82 | _oip = oip; 83 | } 84 | } 85 | 86 | - (NSString *)reqs { 87 | return [NSString stringWithFormat:@"%lld", [_bodySize longLongValue] + [_headerSize longLongValue]]; 88 | } 89 | //- (void)setReqs:(NSString *)reqs { 90 | // if (!_reqs) { 91 | // _reqs = reqs; 92 | // } else { 93 | // _reqs = [NSString stringWithFormat:@"%lld", [reqs longLongValue] + [_reqs longLongValue]]; 94 | // } 95 | //} 96 | 97 | - (void)setState:(NSString *)state { 98 | if (!_state) { 99 | _state = state; 100 | } 101 | } 102 | 103 | - (void)setSc:(NSString *)sc { 104 | if (!_sc) { 105 | _sc = sc; 106 | } 107 | } 108 | 109 | - (void)setEtp:(NSString *)etp { 110 | if (!_etp) { 111 | _etp = etp; 112 | } 113 | } 114 | 115 | - (void)setEc:(NSString *)ec { 116 | if (!_ec) { 117 | _ec = ec; 118 | } 119 | } 120 | 121 | - (void)setEd:(NSString *)ed { 122 | if (!_ed) { 123 | _ed = ed; 124 | } 125 | } 126 | 127 | - (void)setCty:(NSString *)cty { 128 | if (!_cty) { 129 | _cty = cty; 130 | } 131 | } 132 | 133 | - (void)setDdata:(NSString *)ddata { 134 | if (!_ddata) { 135 | _ddata = ddata; 136 | } 137 | } 138 | 139 | - (void)setRess:(NSString *)ress { 140 | if (!_ress) { 141 | _ress = ress; 142 | } else { 143 | _ress = [NSString stringWithFormat:@"%lld", [ress longLongValue] + [_ress longLongValue]]; 144 | } 145 | } 146 | 147 | - (void)setRequestHeaderSize:(NSString *)size { 148 | _headerSize = size; 149 | } 150 | 151 | - (void)setRequestBodySize:(NSString *)size { 152 | _bodySize = size; 153 | } 154 | 155 | 156 | 157 | @end 158 | -------------------------------------------------------------------------------- /NetworkMonitor/NetworkMonitor/NMCache/NMModelCommon.h: -------------------------------------------------------------------------------- 1 | // 2 | // NMModelCommon.h 3 | // NetworkMonitor 4 | // 5 | // Created by frog78 on 2018/4/24. 6 | // Copyright © 2018年 frog78. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @interface NMModelCommon : NSObject 12 | 13 | /** 14 | 把模型转为字典方法 15 | 16 | @return 返回模型转字典结果 17 | */ 18 | - (NSDictionary *)toDictionary; 19 | 20 | /** 21 | 获取所有的属性key 22 | 23 | @return 返回所有的属性key数组 24 | */ 25 | //- (NSArray *)getAllKeys; 26 | 27 | /** 28 | 字典转化为模型 29 | 30 | @param dic 字典 31 | @return 返回模型 32 | */ 33 | + (NMModelCommon *)toModel:(NSDictionary *)dic; 34 | 35 | 36 | @end 37 | -------------------------------------------------------------------------------- /NetworkMonitor/NetworkMonitor/NMCache/NMModelCommon.m: -------------------------------------------------------------------------------- 1 | // 2 | // NMModelCommon.m 3 | // NetworkMonitor 4 | // 5 | // Created by frog78 on 2018/4/24. 6 | // Copyright © 2018年 frog78. All rights reserved. 7 | // 8 | 9 | #import "NMModelCommon.h" 10 | #import 11 | 12 | @implementation NMModelCommon 13 | 14 | - (NSDictionary *)toDictionary { 15 | NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithCapacity:0]; 16 | // 获取当前类的所有属性 17 | unsigned int count;// 记录属性个数 18 | objc_property_t *properties = class_copyPropertyList([self class], &count); 19 | 20 | for (int i = 0; i < count; i++) { 21 | // objc_property_t 属性类型 22 | objc_property_t property = properties[i]; 23 | // 获取属性的名称 C语言字符串 24 | const char *cName = property_getName(property); 25 | // 转换为Objective C 字符串 26 | NSString *name = [NSString stringWithCString:cName encoding:NSUTF8StringEncoding]; 27 | id value = [self valueForKey:name]; 28 | 29 | if (value) { 30 | if ([value isKindOfClass:[NSDictionary class]]) { 31 | [dic addEntriesFromDictionary:value]; 32 | } else { 33 | [dic setValue:value forKey:name]; 34 | } 35 | } 36 | } 37 | free(properties); 38 | return dic; 39 | } 40 | 41 | + (NMModelCommon *)toModel:(NSDictionary *)dic { 42 | 43 | NMModelCommon *model = [[[self class] alloc] init]; 44 | // 获取当前类的所有属性 45 | unsigned int count;// 记录属性个数 46 | objc_property_t *properties = class_copyPropertyList([self class], &count); 47 | 48 | for (int i = 0; i < count; i++) { 49 | // objc_property_t 属性类型 50 | objc_property_t property = properties[i]; 51 | // 获取属性的名称 C语言字符串 52 | const char *cName = property_getName(property); 53 | // 转换为Objective C 字符串 54 | NSString *name = [NSString stringWithCString:cName encoding:NSUTF8StringEncoding]; 55 | 56 | id value = dic[name]; 57 | 58 | if (value) { 59 | [model setValue:value forKey:name]; 60 | } 61 | } 62 | free(properties); 63 | return model; 64 | } 65 | 66 | @end 67 | -------------------------------------------------------------------------------- /NetworkMonitor/NetworkMonitor/NMCore/NMConfig.h: -------------------------------------------------------------------------------- 1 | // 2 | // NMConfig.h 3 | // NetworkMonitor 4 | // 5 | // Created by frog78 on 2018/4/24. 6 | // Copyright © 2018年 frog78. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | /** 12 | @class NMConfig 13 | @abstract NetworkMonitor配置项 14 | */ 15 | @interface NMConfig : NSObject 16 | 17 | /** 18 | 是否开启监控,默认为NO; 19 | */ 20 | @property (nonatomic, assign) BOOL enableNetworkMonitor; 21 | 22 | /** 23 | 是否开启log,默认为YES; 24 | */ 25 | @property (nonatomic, assign) BOOL enableLog; 26 | 27 | /** 28 | 是否开启干扰模式,默认为NO; 29 | 非干扰模式下,记录结束时间由SDK决定; 30 | 干扰模式下,记录结束由开发者手动触发 31 | */ 32 | @property (nonatomic, assign) BOOL enableInterferenceMode; 33 | 34 | /** 35 | 排除在监控之外的url列表 36 | */ 37 | @property (nonatomic, strong) NSArray *urlWhiteList; 38 | 39 | /** 40 | 排除在监控之外的cmd列表 41 | */ 42 | @property (nonatomic, strong) NSArray *cmdWhiteList; 43 | 44 | 45 | @end 46 | -------------------------------------------------------------------------------- /NetworkMonitor/NetworkMonitor/NMCore/NMConfig.m: -------------------------------------------------------------------------------- 1 | // 2 | // NMConfig.m 3 | // NetworkMonitor 4 | // 5 | // Created by frog78 on 2018/4/24. 6 | // Copyright © 2018年 frog78. All rights reserved. 7 | // 8 | 9 | #import "NMConfig.h" 10 | 11 | 12 | @implementation NMConfig 13 | 14 | - (instancetype)init { 15 | self = [super init]; 16 | if (self) { 17 | self.enableLog = YES; 18 | self.enableNetworkMonitor = NO; 19 | self.enableInterferenceMode = NO; 20 | [[NSUserDefaults standardUserDefaults] setBool:NO forKey:IS_NetworkMonitor_ON]; 21 | } 22 | return self; 23 | } 24 | 25 | - (void)setUrlWhiteList:(NSArray *)urlWhiteList { 26 | if (!urlWhiteList) { 27 | return; 28 | } 29 | NSMutableArray *array = [NSMutableArray arrayWithCapacity:0]; 30 | for (NSString *urlStr in urlWhiteList) { 31 | if ([NSURL URLWithString:urlStr].host) { 32 | [array addObject:urlStr]; 33 | } 34 | } 35 | _urlWhiteList = array; 36 | } 37 | 38 | 39 | @end 40 | -------------------------------------------------------------------------------- /NetworkMonitor/NetworkMonitor/NMCore/NMManager.h: -------------------------------------------------------------------------------- 1 | // 2 | // NMManager.h 3 | // NetworkMonitor 4 | // 5 | // Created by frog78 on 2018/4/24. 6 | // Copyright © 2018年 frog78. All rights reserved. 7 | // 8 | 9 | #import 10 | #import "NetworkMonitorDef.h" 11 | #import "NMConfig.h" 12 | 13 | @interface NMManager : NSObject 14 | 15 | /** 16 | 监控数据输出block 17 | 设置了该block,SDK每收集一条完整数据,就会通过该block回调出去 18 | 如果不设置该block,SDK收集的数据将缓存在数据库中 19 | */ 20 | @property (nonatomic, copy) DataOutputBlock outputBlock; 21 | 22 | /** 23 | 获取单例 24 | 25 | @return 返回实例 26 | */ 27 | + (instancetype)sharedNMManager; 28 | 29 | /** 30 | 初始化配置 31 | 32 | @param config NetworkMonitor相关参数配置 33 | */ 34 | - (void)initConfig:(NMConfig *)config; 35 | 36 | 37 | 38 | @end 39 | -------------------------------------------------------------------------------- /NetworkMonitor/NetworkMonitor/NMCore/NMManager.m: -------------------------------------------------------------------------------- 1 | // 2 | // NMManager.m 3 | // NetworkMonitor 4 | // 5 | // Created by frog78 on 2018/4/24. 6 | // Copyright © 2018年 frog78. All rights reserved. 7 | // 8 | 9 | #import "NMManager.h" 10 | #import "NSURLSession+NM.h" 11 | #import "NSURLConnection+NM.h" 12 | #import "NMCache.h" 13 | 14 | @interface NMManager() 15 | 16 | @property (nonatomic, strong) NMConfig *NMConfig; 17 | 18 | @end 19 | 20 | @implementation NMManager 21 | 22 | + (instancetype)sharedNMManager { 23 | static NMManager *manager = nil; 24 | static dispatch_once_t onceToken; 25 | dispatch_once(&onceToken, ^{ 26 | manager = [[NMManager alloc] init]; 27 | }); 28 | return manager; 29 | } 30 | 31 | 32 | - (void)initConfig:(NMConfig *)config { 33 | self.NMConfig = config; 34 | } 35 | 36 | 37 | - (void)start { 38 | if (self.NMConfig.enableNetworkMonitor && ![NMUtil isNetworkMonitorOn]) { 39 | static dispatch_once_t onceToken; 40 | dispatch_once(&onceToken, ^{ 41 | [NSURLSession hook]; 42 | [NSURLConnection hook]; 43 | }); 44 | [[NSUserDefaults standardUserDefaults] setBool:YES forKey:IS_NetworkMonitor_ON]; 45 | } 46 | } 47 | 48 | 49 | - (void)stop { 50 | if (self.NMConfig.enableNetworkMonitor && [NMUtil isNetworkMonitorOn]) { 51 | [[NSUserDefaults standardUserDefaults] setBool:NO forKey:IS_NetworkMonitor_ON]; 52 | } 53 | } 54 | 55 | 56 | - (NMConfig *)getConfig { 57 | return _NMConfig; 58 | } 59 | 60 | - (void)setExtendedParameter:(NSDictionary *)params traceId:(NSString *)traceId { 61 | if (_NMConfig.enableInterferenceMode) { 62 | [[NMCache sharedNMCache] cacheExtension:params traceId:traceId]; 63 | } 64 | } 65 | 66 | - (void)finishColection:(NSString *)traceId { 67 | if (_NMConfig.enableInterferenceMode) { 68 | [[NMCache sharedNMCache] persistData:traceId]; 69 | } 70 | } 71 | 72 | - (NSArray *)getAllData { 73 | return [[NMCache sharedNMCache] getAllData]; 74 | } 75 | 76 | - (void)removeAllData { 77 | [[NMCache sharedNMCache] removeAllData]; 78 | } 79 | 80 | 81 | @end 82 | -------------------------------------------------------------------------------- /NetworkMonitor/NetworkMonitor/NMCore/NSURL+NM.h: -------------------------------------------------------------------------------- 1 | // 2 | // NSURL+NM.h 3 | // NetworkMonitor 4 | // 5 | // Created by frog78 on 2018/5/14. 6 | // Copyright © 2018年 frog78. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | /** 12 | 此NSURL分类用于添加业务扩展参数 13 | 有些业务参数不方便在拦截网络请求时获取(例如:接口描述cmd),需要业务 14 | 手动添加。通过setExtendedParameter:方法添加在NSURL中的扩展参数, 15 | 将被记录在该次请求的监控数据中。 16 | */ 17 | @interface NSURL (NM) 18 | 19 | //在NSURL中添加扩展参数 20 | @property (nonatomic, strong) NSDictionary *extendedParameter; 21 | 22 | 23 | @end 24 | -------------------------------------------------------------------------------- /NetworkMonitor/NetworkMonitor/NMCore/NSURL+NM.m: -------------------------------------------------------------------------------- 1 | // 2 | // NSURL+NM.m 3 | // NetworkMonitor 4 | // 5 | // Created by frog78 on 2018/5/14. 6 | // Copyright © 2018年 frog78. All rights reserved. 7 | // 8 | 9 | #import "NSURL+NM.h" 10 | #import 11 | 12 | 13 | static char *NSURLNMKey = "NSURLNMKey"; 14 | 15 | @implementation NSURL (NM) 16 | 17 | - (void)setExtendedParameter:(NSDictionary *)extendedParameter { 18 | objc_setAssociatedObject(self, NSURLNMKey, extendedParameter, OBJC_ASSOCIATION_RETAIN_NONATOMIC); 19 | } 20 | 21 | - (NSDictionary *)extendedParameter { 22 | return objc_getAssociatedObject(self, NSURLNMKey); 23 | } 24 | 25 | 26 | @end 27 | -------------------------------------------------------------------------------- /NetworkMonitor/NetworkMonitor/NMCore/NetworkMonitorDef.h: -------------------------------------------------------------------------------- 1 | // 2 | // NetworkMonitorDef.h 3 | // NetworkMonitor 4 | // 5 | // Created by frog78 on 2018/4/24. 6 | // Copyright © 2018年 frog78. All rights reserved. 7 | // 8 | 9 | #ifndef NetworkMonitorDef_h 10 | #define NetworkMonitorDef_h 11 | 12 | #define HEAD_KEY_EETRACEID @"head_key_traceid" 13 | #define HEAD_KEY_MAKE(key) [NSString stringWithFormat:@"head_keys_%@", key] 14 | 15 | extern NSString *NMDATA_KEY_CMD; //接口描述 16 | extern NSString *NMDATA_KEY_ERRORTYPE; //错误类型 17 | extern NSString *NMDATA_KEY_RESPONSEDATA; //返回包(状态为失败时记录) 18 | extern NSString *NMDATA_KEY_ORIGINALMD5; //原始md5信息 19 | extern NSString *NMDATA_KEY_DOWNLOADMD5; //下载成功文件的md5信息 20 | extern NSString *NMDATA_KEY_ORIGINALSIZE; //原始文件大小 21 | extern NSString *NMDATA_KEY_DOWNLOADSIZE; //下载成功文件的文件大小 22 | extern NSString *NMDATA_KEY_REALDOWNLOADSIZE; //实际下载大小(md5不一致时记录) 23 | 24 | //监控数据输出block定义 25 | typedef void(^DataOutputBlock)(NSString * traceId, NSDictionary *data); 26 | 27 | @class NMConfig; 28 | 29 | /** 30 | NetworkMonitor对外接口 31 | */ 32 | @protocol NetworkMonitorProtocol 33 | 34 | /** 35 | 开始监控 36 | */ 37 | - (void)start; 38 | 39 | /** 40 | 停止监控 41 | */ 42 | - (void)stop; 43 | 44 | /** 45 | 获取到当前配置 46 | 47 | @return 返回当前配置实例 48 | */ 49 | - (NMConfig *)getConfig; 50 | 51 | #pragma mark-以下接口在干预模式下有效 52 | /** 53 | 根据traceId添加扩展参数 54 | 55 | @abstract 服务端返回的一些业务参数可以通过该方法设置到 56 | 监控记录中。 57 | @param params 业务扩展参数 58 | @param traceId 单次请求唯一id 59 | */ 60 | - (void)setExtendedParameter:(NSDictionary *)params 61 | traceId:(NSString *)traceId; 62 | 63 | /** 64 | 结束本次网络请求数据收集 65 | 66 | @param traceId 单次请求唯一id 67 | */ 68 | - (void)finishColection:(NSString *)traceId; 69 | 70 | #pragma mark-以下接口在不设置outputBlock时有效 71 | /** 72 | 获取所有缓存数据 73 | 74 | @return 返回缓存数据数组 75 | */ 76 | - (NSArray *)getAllData; 77 | 78 | /** 79 | 删除所有缓存数据 80 | */ 81 | - (void)removeAllData; 82 | 83 | 84 | @end 85 | 86 | #endif /* NetworkMonitorDef_h */ 87 | -------------------------------------------------------------------------------- /NetworkMonitor/NetworkMonitor/NMDatabase/DAO/BaseDAO.h: -------------------------------------------------------------------------------- 1 | // 2 | // BaseDAO.h 3 | // DripHttpDNSSDK 4 | // 5 | // Created by frog78 on 2017/11/15. 6 | // Copyright © 2017年 frog78. All rights reserved. 7 | // 8 | 9 | #import 10 | #import 11 | 12 | @interface BaseDAO : NSObject 13 | 14 | @property (strong, nonatomic) NSManagedObjectContext *context; 15 | @property (strong, nonatomic) NSManagedObjectModel *model; 16 | @property (strong, nonatomic) NSPersistentStoreCoordinator *coordinator; 17 | 18 | - (NSURL *)applicationDocumentsDirectory; 19 | 20 | - (NSManagedObjectModel *)managedObjectModel; 21 | 22 | - (NSPersistentStoreCoordinator *)persistentStoreCoordinator; 23 | 24 | - (NSManagedObjectContext *)managedObjectContext; 25 | 26 | - (void)saveContext; 27 | 28 | @end 29 | -------------------------------------------------------------------------------- /NetworkMonitor/NetworkMonitor/NMDatabase/DAO/BaseDAO.m: -------------------------------------------------------------------------------- 1 | // 2 | // BaseDAO.m 3 | // DripHttpDNSSDK 4 | // 5 | // Created by frog78 on 2017/11/15. 6 | // Copyright © 2017年 frog78. All rights reserved. 7 | // 8 | 9 | #import "BaseDAO.h" 10 | 11 | #define XCDATAMODELD_NAME @"NetworkMonitor" 12 | 13 | @implementation BaseDAO 14 | 15 | - (NSURL *)applicationDocumentsDirectory { 16 | 17 | return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject]; 18 | } 19 | 20 | - (NSManagedObjectModel *)managedObjectModel { 21 | 22 | if (_model != nil) { 23 | return _model; 24 | } 25 | NSString *path = [[NSBundle bundleForClass:[self class]] pathForResource:XCDATAMODELD_NAME ofType:@"momd"]; 26 | NSURL *modelURL = [[NSURL alloc] initFileURLWithPath:path]; 27 | _model = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL]; 28 | 29 | return _model; 30 | } 31 | 32 | - (NSPersistentStoreCoordinator *)persistentStoreCoordinator { 33 | 34 | if (_coordinator != nil) { 35 | return _coordinator; 36 | } 37 | 38 | _coordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]]; 39 | 40 | NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:[NSString stringWithFormat:@"%@.sqlite", XCDATAMODELD_NAME]]; 41 | NSError *error = nil; 42 | NSString *failureReason = @"There was an error creating or loading the application's saved data."; 43 | NSDictionary *optionsDictionary = [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES], 44 | NSMigratePersistentStoresAutomaticallyOption, [NSNumber numberWithBool:YES], 45 | NSInferMappingModelAutomaticallyOption, nil]; 46 | if (![_coordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:optionsDictionary error:&error]) { 47 | // Report any error we got. 48 | NSMutableDictionary *dict = [NSMutableDictionary dictionary]; 49 | dict[NSLocalizedDescriptionKey] = @"Failed to initialize the application's saved data"; 50 | dict[NSLocalizedFailureReasonErrorKey] = failureReason; 51 | dict[NSUnderlyingErrorKey] = error; 52 | error = [NSError errorWithDomain:@"YOUR_ERROR_DOMAIN" code:9999 userInfo:dict]; 53 | // Replace this with code to handle the error appropriately. 54 | // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. 55 | EELog(@"Unresolved error %@, %@", error, [error userInfo]); 56 | abort(); 57 | } 58 | 59 | return _coordinator; 60 | } 61 | 62 | 63 | - (NSManagedObjectContext *)managedObjectContext { 64 | // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) 65 | if (_context != nil) { 66 | return _context; 67 | } 68 | 69 | NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator]; 70 | if (!coordinator) { 71 | return nil; 72 | } 73 | _context = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSPrivateQueueConcurrencyType]; 74 | [_context setPersistentStoreCoordinator:coordinator]; 75 | 76 | return _context; 77 | } 78 | 79 | #pragma mark - Core Data Saving support 80 | 81 | - (void)saveContext { 82 | NSManagedObjectContext *managedObjectContext = self.managedObjectContext; 83 | if (managedObjectContext != nil) { 84 | NSError *error = nil; 85 | if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) { 86 | // Replace this implementation with code to handle the error appropriately. 87 | // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. 88 | EELog(@"Unresolved error %@, %@", error, [error userInfo]); 89 | abort(); 90 | } 91 | } 92 | } 93 | 94 | 95 | @end 96 | -------------------------------------------------------------------------------- /NetworkMonitor/NetworkMonitor/NMDatabase/DAO/NMDataDAO.h: -------------------------------------------------------------------------------- 1 | // 2 | // NMDATADAO.h 3 | // NetworkMonitor 4 | // 5 | // Created by frog78 on 2018/4/24. 6 | // Copyright © 2018年 frog78. All rights reserved. 7 | // 8 | 9 | #import "BaseDAO.h" 10 | #import "NMDataModel.h" 11 | #import "NMData+CoreDataProperties.h" 12 | 13 | @interface NMDataDAO : BaseDAO 14 | 15 | /** 16 | 获取单例 17 | 18 | @return 返回单例方法 19 | */ 20 | + (instancetype)share; 21 | 22 | /** 23 | 查询所有数据 24 | 25 | @return 返回所有查询结果 26 | */ 27 | - (NSMutableArray *)findAll; 28 | 29 | /** 30 | 根据traceId查询单条记录 31 | 32 | @param traceId 单条记录唯一id 33 | @return 返回单条的数据记录 34 | */ 35 | - (NMDataModel *)findById:(NSString *)traceId; 36 | 37 | /** 38 | 根据traceId删除单条记录 39 | 40 | @param traceId 单条记录唯一id 41 | @return 返回0删除成功,1删除失败 42 | */ 43 | - (int)removeById:(NSString *)traceId; 44 | 45 | /** 46 | 插入一条数据记录 47 | 48 | @param model 数据记录模型 49 | @return 返回0插入成功,1插入失败 50 | */ 51 | - (int)insert:(NMDataModel *)model; 52 | 53 | /** 54 | 修改一条数据记录 55 | 56 | @abstract 如果数据库里已经存在该条记录,则修改;否则插入 57 | @param model 数据记录模型 58 | @return 返回0修改成功,1修改失败 59 | */ 60 | - (int)modify:(NMDataModel *)model; 61 | 62 | /** 63 | 插入或者修改一条数据记录 64 | 65 | @param model 数据记录模型 66 | @return 返回0成功,1失败 67 | */ 68 | - (int)insertOrModify:(NMDataModel *)model; 69 | 70 | /** 71 | 删除全部缓存数据 72 | 73 | @return 返回0删除成功,1删除失败 74 | */ 75 | - (int)removeAll; 76 | 77 | @end 78 | -------------------------------------------------------------------------------- /NetworkMonitor/NetworkMonitor/NMDatabase/Model/NMData+CoreDataClass.h: -------------------------------------------------------------------------------- 1 | // 2 | // NMDATA+CoreDataClass.h 3 | // 4 | // 5 | // Created by frog78 on 2018/5/10. 6 | // 7 | // 8 | 9 | #import 10 | #import 11 | 12 | @class NSObject; 13 | 14 | NS_ASSUME_NONNULL_BEGIN 15 | 16 | @interface NMData : NSManagedObject 17 | 18 | @end 19 | 20 | NS_ASSUME_NONNULL_END 21 | 22 | #import "NMData+CoreDataProperties.h" 23 | -------------------------------------------------------------------------------- /NetworkMonitor/NetworkMonitor/NMDatabase/Model/NMData+CoreDataClass.m: -------------------------------------------------------------------------------- 1 | // 2 | // NMDATA+CoreDataClass.m 3 | // 4 | // 5 | // Created by frog78 on 2018/5/10. 6 | // 7 | // 8 | 9 | #import "NMData+CoreDataClass.h" 10 | 11 | @implementation NMData 12 | 13 | @end 14 | -------------------------------------------------------------------------------- /NetworkMonitor/NetworkMonitor/NMDatabase/Model/NMData+CoreDataProperties.h: -------------------------------------------------------------------------------- 1 | // 2 | // NMDATA+CoreDataProperties.h 3 | // 4 | // 5 | // Created by frog78 on 2018/5/10. 6 | // 7 | // 8 | 9 | #import "NMData+CoreDataClass.h" 10 | 11 | 12 | NS_ASSUME_NONNULL_BEGIN 13 | 14 | @interface NMData (CoreDataProperties) 15 | 16 | + (NSFetchRequest *)fetchRequest; 17 | 18 | @property (nullable, nonatomic, retain) NSObject *extension; 19 | @property (nullable, nonatomic, copy) NSString *ti; 20 | @property (nullable, nonatomic, copy) NSString *ec; 21 | @property (nullable, nonatomic, copy) NSString *etp; 22 | @property (nullable, nonatomic, copy) NSString *sc; 23 | @property (nullable, nonatomic, copy) NSString *state; 24 | @property (nullable, nonatomic, copy) NSString *reqs; 25 | @property (nullable, nonatomic, copy) NSString *rip; 26 | @property (nullable, nonatomic, copy) NSString *oip; 27 | @property (nullable, nonatomic, copy) NSString *rurl; 28 | @property (nullable, nonatomic, copy) NSString *ourl; 29 | @property (nullable, nonatomic, copy) NSString *cmd; 30 | @property (nullable, nonatomic, copy) NSString *apn; 31 | @property (nullable, nonatomic, copy) NSString *ns; 32 | @property (nullable, nonatomic, copy) NSString *rdsize; 33 | @property (nullable, nonatomic, copy) NSString *dsize; 34 | @property (nullable, nonatomic, copy) NSString *osize; 35 | @property (nullable, nonatomic, copy) NSString *dmd5; 36 | @property (nullable, nonatomic, copy) NSString *omd5; 37 | @property (nullable, nonatomic, copy) NSString *ttt; 38 | @property (nullable, nonatomic, copy) NSString *eres; 39 | @property (nullable, nonatomic, copy) NSString *rcvt; 40 | @property (nullable, nonatomic, copy) NSString *wtt; 41 | @property (nullable, nonatomic, copy) NSString *sdt; 42 | @property (nullable, nonatomic, copy) NSString *cnnt; 43 | @property (nullable, nonatomic, copy) NSString *sslt; 44 | @property (nullable, nonatomic, copy) NSString *dnst; 45 | @property (nullable, nonatomic, copy) NSString *sreq; 46 | @property (nullable, nonatomic, copy) NSString *ddata; 47 | @property (nullable, nonatomic, copy) NSString *cty; 48 | @property (nullable, nonatomic, copy) NSString *ress; 49 | @property (nullable, nonatomic, copy) NSString *ed; 50 | 51 | @end 52 | 53 | NS_ASSUME_NONNULL_END 54 | -------------------------------------------------------------------------------- /NetworkMonitor/NetworkMonitor/NMDatabase/Model/NMData+CoreDataProperties.m: -------------------------------------------------------------------------------- 1 | // 2 | // NMDATA+CoreDataProperties.m 3 | // 4 | // 5 | // Created by frog78 on 2018/5/10. 6 | // 7 | // 8 | 9 | #import "NMData+CoreDataProperties.h" 10 | 11 | @implementation NMData (CoreDataProperties) 12 | 13 | + (NSFetchRequest *)fetchRequest { 14 | return [[NSFetchRequest alloc] initWithEntityName:@"NMData"]; 15 | } 16 | 17 | @dynamic extension; 18 | @dynamic ti; 19 | @dynamic ec; 20 | @dynamic etp; 21 | @dynamic sc; 22 | @dynamic state; 23 | @dynamic reqs; 24 | @dynamic rip; 25 | @dynamic oip; 26 | @dynamic rurl; 27 | @dynamic ourl; 28 | @dynamic cmd; 29 | @dynamic apn; 30 | @dynamic ns; 31 | @dynamic rdsize; 32 | @dynamic dsize; 33 | @dynamic osize; 34 | @dynamic dmd5; 35 | @dynamic omd5; 36 | @dynamic ttt; 37 | @dynamic eres; 38 | @dynamic rcvt; 39 | @dynamic wtt; 40 | @dynamic sdt; 41 | @dynamic cnnt; 42 | @dynamic sslt; 43 | @dynamic dnst; 44 | @dynamic sreq; 45 | @dynamic ddata; 46 | @dynamic cty; 47 | @dynamic ress; 48 | @dynamic ed; 49 | 50 | @end 51 | -------------------------------------------------------------------------------- /NetworkMonitor/NetworkMonitor/NMDatabase/NetworkMonitor.xcdatamodeld/EagleEye.xcdatamodel/contents: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | -------------------------------------------------------------------------------- /NetworkMonitor/NetworkMonitor/NMUtil/NMUtil.h: -------------------------------------------------------------------------------- 1 | // 2 | // NMUtil.h 3 | // NetworkMonitor 4 | // 5 | // Created by frog78 on 2018/4/24. 6 | // Copyright © 2018年 frog78. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @interface NMUtil : NSObject 12 | 13 | /** 14 | 获取唯一traceId 15 | 16 | @return 返回traceId 17 | */ 18 | + (NSString *)getTraceId; 19 | 20 | /** 21 | 是否开始监控 22 | 23 | @return 返回结果 24 | */ 25 | + (BOOL)isNetworkMonitorOn; 26 | 27 | /** 28 | 是否为干预模式 29 | 30 | @return 返回结果 31 | */ 32 | + (BOOL)isInterferenceMode; 33 | 34 | /** 35 | 获取当前网络类型 36 | 37 | @return 返回网络类型 38 | */ 39 | + (NSString *)getNetWorkInfo; 40 | 41 | /** 42 | 获取当前网络强度 43 | 44 | @return 返回网络强度 45 | */ 46 | + (NSString *)getSignalStrength; 47 | 48 | /** 49 | 检测是否为域名 50 | 51 | @param domain 域名 52 | @return 返回检测结果 53 | */ 54 | + (BOOL)isDomain:(NSString *)domain; 55 | 56 | /** 57 | 通过域名获取ip 58 | 59 | @param domain 域名 60 | @return 返回本地域名解析结果 61 | */ 62 | + (NSString *)getIPByDomain:(const NSString *)domain; 63 | 64 | /** 65 | 从请求头中提取参数 66 | 67 | @param headerField 请求头中headerField 68 | @return 返回提取到的特定参数 69 | */ 70 | + (NSDictionary *)extractParamsFromHeader:(NSDictionary *)headerField; 71 | 72 | /** 73 | 获取文件大小 74 | 75 | @param path 文件路径 76 | @param error 错误 77 | @return 返回文件大小结果 78 | */ 79 | + (NSNumber *)sizeOfItemAtPath:(NSString *)path error:(NSError *__autoreleasing *)error; 80 | 81 | /** 82 | 获取当前时间戳 83 | 84 | @return 返回当前时间戳 85 | */ 86 | + (NSString *)getCurrentTime; 87 | 88 | /** 89 | 请求转为可变请求 90 | 91 | @abstract 如果原来就是可变请求则强转,如果不是则用mutablecopy 92 | @param request 原请求 93 | @return 可变请求 94 | */ 95 | + (NSMutableURLRequest *)mutableRequest:(NSURLRequest *)request; 96 | 97 | /** 98 | * 获取运营商网络的详细接入点信息,其无法根据当前网络状态进行区分,外部使用时需要注意 99 | * 100 | * @return 详细接入点信息 101 | */ 102 | + (NSString *)getDetailApCode; 103 | 104 | /** 105 | 系统版本是否大于等于10.0 106 | 107 | @return 返回判断值 108 | */ 109 | + (BOOL)isAbove_iOS_10_0; 110 | 111 | /** 112 | 根据文件后缀获取mimetype 113 | 114 | @param type 文件后缀 115 | @return 返回mimetype值 116 | */ 117 | + (NSString *)mimeType:(NSString *)type; 118 | 119 | 120 | @end 121 | -------------------------------------------------------------------------------- /NetworkMonitor/NetworkMonitor/NMUtil/NSData+GZIP.h: -------------------------------------------------------------------------------- 1 | // 2 | // GZIP.h 3 | // 4 | // Version 1.2.1 5 | // 6 | // Created by Nick Lockwood on 03/06/2012. 7 | // Copyright (C) 2012 Charcoal Design 8 | // 9 | // Distributed under the permissive zlib License 10 | // Get the latest version from here: 11 | // 12 | // https://github.com/nicklockwood/GZIP 13 | // 14 | // This software is provided 'as-is', without any express or implied 15 | // warranty. In no event will the authors be held liable for any damages 16 | // arising from the use of this software. 17 | // 18 | // Permission is granted to anyone to use this software for any purpose, 19 | // including commercial applications, and to alter it and redistribute it 20 | // freely, subject to the following restrictions: 21 | // 22 | // 1. The origin of this software must not be misrepresented; you must not 23 | // claim that you wrote the original software. If you use this software 24 | // in a product, an acknowledgment in the product documentation would be 25 | // appreciated but is not required. 26 | // 27 | // 2. Altered source versions must be plainly marked as such, and must not be 28 | // misrepresented as being the original software. 29 | // 30 | // 3. This notice may not be removed or altered from any source distribution. 31 | // 32 | 33 | 34 | #import 35 | 36 | 37 | @interface NSData (GZIP) 38 | 39 | - (nullable NSData *)gzippedDataWithCompressionLevel:(float)level; 40 | - (nullable NSData *)gzippedData; 41 | - (nullable NSData *)gunzippedData; 42 | - (BOOL)isGzippedData; 43 | 44 | @end 45 | -------------------------------------------------------------------------------- /NetworkMonitor/NetworkMonitor/NMUtil/NSData+GZIP.m: -------------------------------------------------------------------------------- 1 | // 2 | // GZIP.m 3 | // 4 | // Version 1.2.1 5 | // 6 | // Created by Nick Lockwood on 03/06/2012. 7 | // Copyright (C) 2012 Charcoal Design 8 | // 9 | // Distributed under the permissive zlib License 10 | // Get the latest version from here: 11 | // 12 | // https://github.com/nicklockwood/GZIP 13 | // 14 | // This software is provided 'as-is', without any express or implied 15 | // warranty. In no event will the authors be held liable for any damages 16 | // arising from the use of this software. 17 | // 18 | // Permission is granted to anyone to use this software for any purpose, 19 | // including commercial applications, and to alter it and redistribute it 20 | // freely, subject to the following restrictions: 21 | // 22 | // 1. The origin of this software must not be misrepresented; you must not 23 | // claim that you wrote the original software. If you use this software 24 | // in a product, an acknowledgment in the product documentation would be 25 | // appreciated but is not required. 26 | // 27 | // 2. Altered source versions must be plainly marked as such, and must not be 28 | // misrepresented as being the original software. 29 | // 30 | // 3. This notice may not be removed or altered from any source distribution. 31 | // 32 | 33 | 34 | #import "NSData+GZIP.h" 35 | #import 36 | 37 | 38 | #pragma clang diagnostic ignored "-Wcast-qual" 39 | 40 | 41 | @implementation NSData (GZIP) 42 | 43 | - (NSData *)gzippedDataWithCompressionLevel:(float)level 44 | { 45 | if (self.length == 0 || [self isGzippedData]) 46 | { 47 | return self; 48 | } 49 | 50 | z_stream stream; 51 | stream.zalloc = Z_NULL; 52 | stream.zfree = Z_NULL; 53 | stream.opaque = Z_NULL; 54 | stream.avail_in = (uint)self.length; 55 | stream.next_in = (Bytef *)(void *)self.bytes; 56 | stream.total_out = 0; 57 | stream.avail_out = 0; 58 | 59 | static const NSUInteger ChunkSize = 16384; 60 | 61 | NSMutableData *output = nil; 62 | int compression = (level < 0.0f)? Z_DEFAULT_COMPRESSION: (int)(roundf(level * 9)); 63 | if (deflateInit2(&stream, compression, Z_DEFLATED, 31, 8, Z_DEFAULT_STRATEGY) == Z_OK) 64 | { 65 | output = [NSMutableData dataWithLength:ChunkSize]; 66 | while (stream.avail_out == 0) 67 | { 68 | if (stream.total_out >= output.length) 69 | { 70 | output.length += ChunkSize; 71 | } 72 | stream.next_out = (uint8_t *)output.mutableBytes + stream.total_out; 73 | stream.avail_out = (uInt)(output.length - stream.total_out); 74 | deflate(&stream, Z_FINISH); 75 | } 76 | deflateEnd(&stream); 77 | output.length = stream.total_out; 78 | } 79 | 80 | return output; 81 | } 82 | 83 | - (NSData *)gzippedData 84 | { 85 | return [self gzippedDataWithCompressionLevel:-1.0f]; 86 | } 87 | 88 | - (NSData *)gunzippedData 89 | { 90 | if (self.length == 0 || ![self isGzippedData]) 91 | { 92 | return self; 93 | } 94 | 95 | z_stream stream; 96 | stream.zalloc = Z_NULL; 97 | stream.zfree = Z_NULL; 98 | stream.avail_in = (uint)self.length; 99 | stream.next_in = (Bytef *)self.bytes; 100 | stream.total_out = 0; 101 | stream.avail_out = 0; 102 | 103 | NSMutableData *output = nil; 104 | if (inflateInit2(&stream, 47) == Z_OK) 105 | { 106 | int status = Z_OK; 107 | output = [NSMutableData dataWithCapacity:self.length * 2]; 108 | while (status == Z_OK) 109 | { 110 | if (stream.total_out >= output.length) 111 | { 112 | output.length += self.length / 2; 113 | } 114 | stream.next_out = (uint8_t *)output.mutableBytes + stream.total_out; 115 | stream.avail_out = (uInt)(output.length - stream.total_out); 116 | status = inflate (&stream, Z_SYNC_FLUSH); 117 | } 118 | if (inflateEnd(&stream) == Z_OK) 119 | { 120 | if (status == Z_STREAM_END) 121 | { 122 | output.length = stream.total_out; 123 | } 124 | } 125 | } 126 | 127 | return output; 128 | } 129 | 130 | - (BOOL)isGzippedData 131 | { 132 | const UInt8 *bytes = (const UInt8 *)self.bytes; 133 | return (self.length >= 2 && bytes[0] == 0x1f && bytes[1] == 0x8b); 134 | } 135 | 136 | @end 137 | -------------------------------------------------------------------------------- /NetworkMonitor/NetworkMonitor/NetworkMonitor.h: -------------------------------------------------------------------------------- 1 | // 2 | // NetworkMonitor.h 3 | // NetworkMonitor 4 | // 5 | // Created by frog78 on 2018/8/16. 6 | // Copyright © 2018年 frog78. All rights reserved. 7 | // 8 | 9 | #import 10 | #import 11 | #import 12 | #import 13 | #import 14 | 15 | //! Project version number for NetworkMonitor. 16 | FOUNDATION_EXPORT double NetworkMonitorVersionNumber; 17 | 18 | //! Project version string for NetworkMonitor. 19 | FOUNDATION_EXPORT const unsigned char NetworkMonitorVersionString[]; 20 | 21 | // In this header, you should import all the public headers of your framework using statements like #import 22 | 23 | 24 | -------------------------------------------------------------------------------- /NetworkMonitor/NetworkMonitor/NetworkMonitor.pch: -------------------------------------------------------------------------------- 1 | // 2 | // NetworkMonitor.pch 3 | // NetworkMonitor 4 | // 5 | // Created by frog78 on 2018/4/24. 6 | // Copyright © 2018年 frog78. All rights reserved. 7 | // 8 | 9 | #ifndef NetworkMonitor_pch 10 | #define NetworkMonitor_pch 11 | 12 | #import "NMHooker.h" 13 | #import "NMUtil.h" 14 | #import "NMManager.h" 15 | 16 | #define IS_NetworkMonitor_ON @"is_NetworkMonitor_on" 17 | 18 | 19 | #ifdef DEBUG 20 | 21 | #define EEXLog(fmt, ...) NSLog((@"*NetworkMonitor*:[Line %d] %s " fmt), __LINE__, __PRETTY_FUNCTION__, ##__VA_ARGS__); 22 | 23 | #else 24 | 25 | #define EEXLog(...) 26 | 27 | #endif 28 | 29 | 30 | #define EELog(fmt, ...) {\ 31 | if ([[NMManager sharedNMManager] getConfig].enableLog) { \ 32 | EEXLog(@"%@", [NSString stringWithFormat:fmt, ##__VA_ARGS__]); \ 33 | } \ 34 | } 35 | 36 | 37 | #endif /* NetworkMonitor_pch */ 38 | -------------------------------------------------------------------------------- /NetworkMonitor/NetworkMonitorTests/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | $(DEVELOPMENT_LANGUAGE) 7 | CFBundleExecutable 8 | $(EXECUTABLE_NAME) 9 | CFBundleIdentifier 10 | $(PRODUCT_BUNDLE_IDENTIFIER) 11 | CFBundleInfoDictionaryVersion 12 | 6.0 13 | CFBundleName 14 | $(PRODUCT_NAME) 15 | CFBundlePackageType 16 | BNDL 17 | CFBundleShortVersionString 18 | 1.0 19 | CFBundleVersion 20 | 1 21 | 22 | 23 | -------------------------------------------------------------------------------- /NetworkMonitor/NetworkMonitorTests/NetworkMonitorTests.m: -------------------------------------------------------------------------------- 1 | // 2 | // NetworkMonitorTests.m 3 | // NetworkMonitorTests 4 | // 5 | // Created by frog78 on 2018/8/16. 6 | // Copyright © 2018年 frog78. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @interface NetworkMonitorTests : XCTestCase 12 | 13 | @end 14 | 15 | @implementation NetworkMonitorTests 16 | 17 | - (void)setUp { 18 | [super setUp]; 19 | // Put setup code here. This method is called before the invocation of each test method in the class. 20 | } 21 | 22 | - (void)tearDown { 23 | // Put teardown code here. This method is called after the invocation of each test method in the class. 24 | [super tearDown]; 25 | } 26 | 27 | - (void)testExample { 28 | // This is an example of a functional test case. 29 | // Use XCTAssert and related functions to verify your tests produce the correct results. 30 | } 31 | 32 | - (void)testPerformanceExample { 33 | // This is an example of a performance test case. 34 | [self measureBlock:^{ 35 | // Put the code you want to measure the time of here. 36 | }]; 37 | } 38 | 39 | @end 40 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # NetworkMonitor 2 | 3 | ## 简介 4 | NetworkMonitor主要用于监控应用的网络请求,获取网络请求相关的性能参数,方便开发、测试、产品等人员对应用进行分析。监控的指标主要有:成功率、状态码、流量、网络响应时间、HTTP与HTTPS的 DNS 解析、TCP握手、SSL握手(HTTPS)等。 5 | NetworkMonitor的优点主要有: 6 | * 收集数据全面。主要监控参数如上所述,基本涵盖了网络监控需求。 7 | * 监控范围广。基本涵盖了应用层的网络请求,但是UIWebView/WKWebView除外,这个是后续开发方向。 8 | * 接入使用方便。采用无埋点的数据收集方式,用户不需要手动埋点,接入只需要几行代码,即可收集基本数据。 9 | * 可扩展性强。除了基本参数之外,用户还可以自定义扩展参数。 10 | * 简洁轻量。SDK包大小不到0.5M,运行内存小,不挤占主应用资源。 11 | * 数据准确度较高。SDK尽可能地使用了系统提供的数据,对于自己计算得到的数据,都经过了校准调优。 12 | 13 | ## 原理及设计 14 | 见 [iOS端网络监控思路及实现](https://www.jianshu.com/p/3bdb027a63c7) 15 | 16 | ## 集成使用 17 | 18 | ### 导入SDK 19 | 将NetworkMonitor.framework导入到工程中,并在工程配置中General—>Embedded Binaries中添加该framework。 20 | 21 | ### SDK使用 22 | 1、初始化配置 23 | 网络监控配置项都封装在NMConfig类中,通过执行以下代码初始化配置。 24 | ``` 25 | NMConfig *config = [[NMConfig alloc] init]; 26 | config.enableNetworkMonitor = YES; 27 | config.enableLog = YES; 28 | … 29 | [[NMManager sharedNMManager] initConfig:config]; 30 | ``` 31 | 配置项说明: 32 | - enableNetworkMonitor:监控总开关,默认为NO。如果配置为NO,NetworkMonitor中任何代码都不会运行。 33 | - enableLog:日志开关,默认为YES。 34 | - enableInterferenceMode:是否开启干扰模式,默认为NO;非干扰模式下,记录结束时间由SDK决定;干扰模式下,记录结束由用户手动触发。 35 | - urlWhiteList:排除在监控之外的url列表。 36 | - cmdWhiteList:排除在监控之外的cmd(即接口方法)列表。 37 | 38 | 2、开始/结束监控 39 | 完成初始化配置之后,调用NMManager中的开始/停止方法,就可以启动/关闭监控了。 40 | 开始监控: 41 | ``` 42 | [[NMManager sharedNMManager] start]; 43 | ``` 44 | 停止监控: 45 | ``` 46 | [[NMManager sharedNMManager] stop]; 47 | ``` 48 | 49 | 注:start/stop方法是动态开关。执行start之后,NetworkMonitor中所有hook逻辑就执行了。但stop并不是对hook的逆操作,执行stop只是阻止了NetworkMonitor内部进行数据的收集和处理。 50 | 51 | 至此,简单的几步,就可以完成基础默认数据的收集了。 52 | 53 | 3、监控数据的输出 54 | 上面已经完成基础数据的收集了,NetworkMonitor内部是不带数据上传的,那么怎么获取到收集的数据呢?有两种方式: 55 | * 默认方式 56 | 收集到的数据会默认存储在NetworkMonitor内部的数据库。可以通过NetworkMonitor的方法将数据取出。 57 | 对数据操作的方法主要有下面几个: 58 | ``` 59 | NSArray *data = [[NMManager sharedNMManager] getAllData]; 60 | ``` 61 | 获取所有数据。 62 | ``` 63 | [[NMManager sharedNMManager] removeAllData]; 64 | ``` 65 | 删除所有数据。 66 | * 设置数据输出block 67 | ``` 68 | [NMManager sharedNMManager].outputBlock = ^(NSString *traceId, NSDictionary *data){ 69 | } 70 | ``` 71 | 如果设置了outputBlock,默认方式将会失效。而且所有收集到的数据将会一条一条地通过outputBlock回调输出出来,每收集到一条数据回调一次。 72 | 73 | 4、数据收集模式 74 | 数据收集模式有两种,分别是默认模式和干预模式。通过前面介绍的配置项enableInterferenceMode进行设置。这两种模式的主要区别在于,一条网络请求数据收集结束的时间。 75 | 在默认模式下,一条请求数据收集完成,SDK内部会自动结束该次数据的收集。而在干预模式下,需要开发者手动调用以下方法完成数据收集: 76 | ``` 77 | [[NMManager sharedNMManager] finishColection:traceId]; 78 | ``` 79 | 80 | 5、扩展参数设置 81 | 以上介绍的主要是默认的数据收集。但是,这些数据一般是很难满足业务需要。那么怎样将想要的其他数据放在这些基础数据一起进行收集呢?这就要用到扩展参数的设置。 82 | 扩展参数设置又分为网络请求之前参数设置和网络请求之后参数设置。 83 | * 网络请求之前参数设置 84 | 有些参数需要在网络请求发起之前进行设置,例如网络请求接口名(cmd)、设备信息等。NetworkMonitor提供了两种设置网络请求之前参数的方法。 85 | 一种是引入头文件“NSURL+NM.h”,然后把参数绑定在NSURL实例的extendedParameter属性上,如下所示: 86 | ``` 87 | [NSURL *url = [NSURL URLWithString:@"xxx"]; 88 | url.extendedParameter = @{@"cmd":@"xxx"}; 89 | ``` 90 | 另一种情况是,NSURL实例被封装了,外面看不到,例如AFNetworking。这种情况一般可以拿到网络请求头的字典,直接用SDK提供的宏定义HEAD_KEY_MAKE()将key封装一下作为请求头中的key,再把value设置进求头中就可以了。例如: 91 | ``` 92 | NSString * key = @"xxx"; 93 | AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; 94 | [manager.requestSerializer setValue: @"xxx" forHTTPHeaderField:HEAD_KEY_MAKE(key)]; 95 | ``` 96 | * 网络请求之后参数设置 97 | 需要网络请求之后进行设置的参数,一般是网络请求结果或者依赖于网络请求结果的数据,例如:下载文件的md5等。需要注意的是,这种情况一般需要开发者手动结束SDK的数据收集,即配合干预模式使用。 98 | 此时可以调用SDK的setExtendedParameter:方法进行设置。如下所示,需要传入traceId参数,可以从响应头中拿到。 99 | ``` 100 | NSString *traceId = mrq.allHTTPHeaderFields[HEAD_KEY_EETRACEID]; 101 | [[NMManager sharedNMManager] setExtendedParameter:@{@"xxx": @"xxx"} traceId:traceId]; 102 | ``` 103 | 然后需要手动调用finishColection:traceId,以结束数据收集。 104 | ``` 105 | [[NMManager sharedNMManager] finishColection:traceId]; 106 | ``` 107 | 108 | 6、名词解释 109 | traceId:一次网络请求数据记录的唯一标志。 110 | 111 | 干预模式:开发者能够手动干预SDK数据收集的模式。 112 | 113 | 白名单:网络请求url或者同一url下面的不同服务端接口,如果加在了白名单中,那么对该url或者url下面服务端接口的网络请求数据不会被SDK收集。 114 | 115 | SDK定义的一些特定Key: 116 | ``` 117 | NMDATA_KEY_CMD; //接口描述 118 | NMDATA_KEY_ERRORTYPE; //错误类型 119 | NMDATA_KEY_RESPONSEDATA; //返回包(状态为失败时记录) 120 | NMDATA_KEY_ORIGINALMD5; //原始md5信息 121 | NMDATA_KEY_DOWNLOADMD5; //下载成功文件的md5信息 122 | NMDATA_KEY_ORIGINALSIZE; //原始文件大小 123 | NMDATA_KEY_DOWNLOADSIZE; //下载成功文件的文件大小 124 | NMDATA_KEY_REALDOWNLOADSIZE; //实际下载大小(md5不一致时记录) 125 | ``` 126 | 注:在引入NetworkMonitor.framework之后,这些key是可以直接使用的。在拿到这些key对应的value之后,可以直接设置到扩展参数中。 127 | 128 | 7、SDK中参数含义对照表 129 | 130 | | 参数key | 参数含义 | 131 | | ------ | ------ | 132 | | ti | 单次请求的唯一id | 133 | | apn | 当前接入点名称(wifi、cmwap、ctwap、uniwap、cmnet、uninet、ctnet、g3net、g3wap、unknown) | 134 | | ns(networktype) | 网络类型 | 135 | | cmd | 接口描述 | 136 | | ourl(originalUrl) | 原始url | 137 | | rurl(redirectUrl) | 重定向url | 138 | | oip(originalIp) | 原始ip | 139 | | rip(redirectIp) | 重定向ip | 140 | | reqs(requestSize) | 请求包大小 | 141 | | state | 接口请求结果:success、failure、cancel | 142 | | sc(statusCode) | 状态码 | 143 | | etp(errorType) | 错误类型:1网络错误 2http错误 3业务错误 | 144 | | ec(errorCode) | 错误码 | 145 | | ed(errorDetail) | 错误描述 | 146 | | ress(responseSize) | 返回包大小 | 147 | | cty(contentType) | mimeType | 148 | | ddata(responseData) | 返回包(状态为失败时记录) | 149 | | sreq(startRequest) | 请求开始时间 | 150 | | dnst(dnsTime) | 域名解析的时间 | 151 | | sslt(sslTime) | SSL的时间,仅针对https,当http时此项为空 | 152 | | cnnt(connTime) | 与服务器建立tcp链接需要的时间 | 153 | | sdt(sendTime) | 从客户端发送HTTP请求到服务器所耗费的时间 | 154 | | wtt(waitTime) | 响应报文首字节到达时间 | 155 | | rcvt(receiveTime) | 客户端从开始接收数据到接收完所有数据的时间 | 156 | | eres(endResponse) | 响应结束时间 | 157 | | ttt(totalTime) | 请求总耗时 | 158 | | omd5(originalMd5) | 原始md5信息 | 159 | | dmd5(downloadMd5) | 下载成功文件的md5信息 | 160 | | osize(originalSize) | 原始文件大小,单位:字节 | 161 | | dsize(downloadSize) | 下载成功文件的文件大小,单位:字节 | 162 | | rdsize(realDownloadSize) | 实际下载大小(md5不一致时记录),单位:字节 | 163 | --------------------------------------------------------------------------------