FLEXNetworkObserver.m 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197
  1. //
  2. // FLEXNetworkObserver.m
  3. // Derived from:
  4. //
  5. // PDAFNetworkDomainController.m
  6. // PonyDebugger
  7. //
  8. // Created by Mike Lewis on 2/27/12.
  9. //
  10. // Licensed to Square, Inc. under one or more contributor license agreements.
  11. // See the LICENSE file distributed with this work for the terms under
  12. // which Square, Inc. licenses this file to you.
  13. //
  14. #import "FLEXNetworkObserver.h"
  15. #import "FLEXNetworkRecorder.h"
  16. #import <objc/runtime.h>
  17. #import <objc/message.h>
  18. #import <dispatch/queue.h>
  19. NSString *const kFLEXNetworkObserverEnabledStateChangedNotification = @"kFLEXNetworkObserverEnabledStateChangedNotification";
  20. static NSString *const kFLEXNetworkObserverEnableOnLaunchDefaultsKey = @"com.flex.FLEXNetworkObserver.enableOnLaunch";
  21. typedef void (^NSURLSessionAsyncCompletion)(id fileURLOrData, NSURLResponse *response, NSError *error);
  22. @interface FLEXInternalRequestState : NSObject
  23. @property (nonatomic, copy) NSURLRequest *request;
  24. @property (nonatomic, strong) NSMutableData *dataAccumulator;
  25. @end
  26. @implementation FLEXInternalRequestState
  27. @end
  28. @interface FLEXNetworkObserver (NSURLConnectionHelpers)
  29. - (void)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response delegate:(id <NSURLConnectionDelegate>)delegate;
  30. - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response delegate:(id <NSURLConnectionDelegate>)delegate;
  31. - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data delegate:(id <NSURLConnectionDelegate>)delegate;
  32. - (void)connectionDidFinishLoading:(NSURLConnection *)connection delegate:(id <NSURLConnectionDelegate>)delegate;
  33. - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error delegate:(id <NSURLConnectionDelegate>)delegate;
  34. - (void)connectionWillCancel:(NSURLConnection *)connection;
  35. @end
  36. @interface FLEXNetworkObserver (NSURLSessionTaskHelpers)
  37. - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task willPerformHTTPRedirection:(NSHTTPURLResponse *)response newRequest:(NSURLRequest *)request completionHandler:(void (^)(NSURLRequest *))completionHandler delegate:(id <NSURLSessionDelegate>)delegate;
  38. - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler delegate:(id <NSURLSessionDelegate>)delegate;
  39. - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data delegate:(id <NSURLSessionDelegate>)delegate;
  40. - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask
  41. didBecomeDownloadTask:(NSURLSessionDownloadTask *)downloadTask delegate:(id <NSURLSessionDelegate>)delegate;
  42. - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error delegate:(id <NSURLSessionDelegate>)delegate;
  43. - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite delegate:(id <NSURLSessionDelegate>)delegate;
  44. - (void)URLSession:(NSURLSession *)session task:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location data:(NSData *)data delegate:(id <NSURLSessionDelegate>)delegate;
  45. - (void)URLSessionTaskWillResume:(NSURLSessionTask *)task;
  46. @end
  47. @interface FLEXNetworkObserver ()
  48. @property (nonatomic, assign, getter=isEnabled) BOOL enabled;
  49. @property (nonatomic, strong) NSMutableDictionary *requestStatesForRequestIDs;
  50. @property (nonatomic, strong) dispatch_queue_t queue;
  51. @end
  52. @implementation FLEXNetworkObserver
  53. #pragma mark - Public Methods
  54. + (void)setEnabled:(BOOL)enabled
  55. {
  56. if (enabled) {
  57. // Inject if needed. This injection is protected with a dispatch_once, so we're ok calling it multiple times.
  58. // By doing the injection lazily, we keep the impact of the tool lower when this feature isn't enabled.
  59. [self injectIntoAllNSURLConnectionDelegateClasses];
  60. }
  61. [[self sharedObserver] setEnabled:enabled];
  62. }
  63. + (BOOL)isEnabled
  64. {
  65. return [[self sharedObserver] isEnabled];
  66. }
  67. - (void)setEnabled:(BOOL)enabled
  68. {
  69. if (_enabled != enabled) {
  70. _enabled = enabled;
  71. [[NSNotificationCenter defaultCenter] postNotificationName:kFLEXNetworkObserverEnabledStateChangedNotification object:self];
  72. }
  73. }
  74. + (void)setShouldEnableOnLaunch:(BOOL)shouldEnableOnLaunch
  75. {
  76. [[NSUserDefaults standardUserDefaults] setBool:shouldEnableOnLaunch forKey:kFLEXNetworkObserverEnableOnLaunchDefaultsKey];
  77. }
  78. + (BOOL)shouldEnableOnLaunch
  79. {
  80. return [[[NSUserDefaults standardUserDefaults] objectForKey:kFLEXNetworkObserverEnableOnLaunchDefaultsKey] boolValue];
  81. }
  82. + (void)load
  83. {
  84. // We don't want to do the swizzling from +load because not all the classes may be loaded at this point.
  85. dispatch_async(dispatch_get_main_queue(), ^{
  86. if ([self shouldEnableOnLaunch]) {
  87. [self setEnabled:YES];
  88. }
  89. });
  90. }
  91. #pragma mark - Statics
  92. + (instancetype)sharedObserver
  93. {
  94. static FLEXNetworkObserver *sharedObserver = nil;
  95. static dispatch_once_t onceToken;
  96. dispatch_once(&onceToken, ^{
  97. sharedObserver = [[[self class] alloc] init];
  98. });
  99. return sharedObserver;
  100. }
  101. + (NSString *)nextRequestID
  102. {
  103. return [[NSUUID UUID] UUIDString];
  104. }
  105. #pragma mark Delegate Injection Convenience Methods
  106. + (SEL)swizzledSelectorForSelector:(SEL)selector
  107. {
  108. return NSSelectorFromString([NSString stringWithFormat:@"_flex_swizzle_%x_%@", arc4random(), NSStringFromSelector(selector)]);
  109. }
  110. /// All swizzled delegate methods should make use of this guard.
  111. /// This will prevent duplicated sniffing when the original implementation calls up to a superclass implementation which we've also swizzled.
  112. /// The superclass implementation (and implementations in classes above that) will be executed without inteference if called from the original implementation.
  113. + (void)sniffWithoutDuplicationForObject:(NSObject *)object selector:(SEL)selector sniffingBlock:(void (^)(void))sniffingBlock originalImplementationBlock:(void (^)(void))originalImplementationBlock
  114. {
  115. // If we don't have an object to detect nested calls on, just run the original implmentation and bail.
  116. // This case can happen if someone besides the URL loading system calls the delegate methods directly.
  117. // See https://github.com/Flipboard/FLEX/issues/61 for an example.
  118. if (!object) {
  119. originalImplementationBlock();
  120. return;
  121. }
  122. const void *key = selector;
  123. // Don't run the sniffing block if we're inside a nested call
  124. if (!objc_getAssociatedObject(object, key)) {
  125. sniffingBlock();
  126. }
  127. // Mark that we're calling through to the original so we can detect nested calls
  128. objc_setAssociatedObject(object, key, @YES, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
  129. originalImplementationBlock();
  130. objc_setAssociatedObject(object, key, nil, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
  131. }
  132. + (BOOL)instanceRespondsButDoesNotImplementSelector:(SEL)selector class:(Class)cls
  133. {
  134. if ([cls instancesRespondToSelector:selector]) {
  135. unsigned int numMethods = 0;
  136. Method *methods = class_copyMethodList(cls, &numMethods);
  137. BOOL implementsSelector = NO;
  138. for (int index = 0; index < numMethods; index++) {
  139. SEL methodSelector = method_getName(methods[index]);
  140. if (selector == methodSelector) {
  141. implementsSelector = YES;
  142. break;
  143. }
  144. }
  145. free(methods);
  146. if (!implementsSelector) {
  147. return YES;
  148. }
  149. }
  150. return NO;
  151. }
  152. + (void)replaceImplementationOfKnownSelector:(SEL)originalSelector onClass:(Class)class withBlock:(id)block swizzledSelector:(SEL)swizzledSelector
  153. {
  154. // This method is only intended for swizzling methods that are know to exist on the class.
  155. // Bail if that isn't the case.
  156. Method originalMethod = class_getInstanceMethod(class, originalSelector);
  157. if (!originalMethod) {
  158. return;
  159. }
  160. IMP implementation = imp_implementationWithBlock(block);
  161. class_addMethod(class, swizzledSelector, implementation, method_getTypeEncoding(originalMethod));
  162. Method newMethod = class_getInstanceMethod(class, swizzledSelector);
  163. method_exchangeImplementations(originalMethod, newMethod);
  164. }
  165. + (void)replaceImplementationOfSelector:(SEL)selector withSelector:(SEL)swizzledSelector forClass:(Class)cls withMethodDescription:(struct objc_method_description)methodDescription implementationBlock:(id)implementationBlock undefinedBlock:(id)undefinedBlock
  166. {
  167. if ([self instanceRespondsButDoesNotImplementSelector:selector class:cls]) {
  168. return;
  169. }
  170. IMP implementation = imp_implementationWithBlock((id)([cls instancesRespondToSelector:selector] ? implementationBlock : undefinedBlock));
  171. Method oldMethod = class_getInstanceMethod(cls, selector);
  172. if (oldMethod) {
  173. class_addMethod(cls, swizzledSelector, implementation, methodDescription.types);
  174. Method newMethod = class_getInstanceMethod(cls, swizzledSelector);
  175. method_exchangeImplementations(oldMethod, newMethod);
  176. } else {
  177. class_addMethod(cls, selector, implementation, methodDescription.types);
  178. }
  179. }
  180. #pragma mark - Delegate Injection
  181. + (void)injectIntoAllNSURLConnectionDelegateClasses
  182. {
  183. // Only allow swizzling once.
  184. static dispatch_once_t onceToken;
  185. dispatch_once(&onceToken, ^{
  186. // Swizzle any classes that implement one of these selectors.
  187. const SEL selectors[] = {
  188. @selector(connectionDidFinishLoading:),
  189. @selector(connection:willSendRequest:redirectResponse:),
  190. @selector(connection:didReceiveResponse:),
  191. @selector(connection:didReceiveData:),
  192. @selector(connection:didFailWithError:),
  193. @selector(URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:),
  194. @selector(URLSession:dataTask:didReceiveData:),
  195. @selector(URLSession:dataTask:didReceiveResponse:completionHandler:),
  196. @selector(URLSession:task:didCompleteWithError:),
  197. @selector(URLSession:dataTask:didBecomeDownloadTask:delegate:),
  198. @selector(URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:),
  199. @selector(URLSession:downloadTask:didFinishDownloadingToURL:)
  200. };
  201. const int numSelectors = sizeof(selectors) / sizeof(SEL);
  202. Class *classes = NULL;
  203. int numClasses = objc_getClassList(NULL, 0);
  204. if (numClasses > 0) {
  205. classes = (__unsafe_unretained Class *)malloc(sizeof(Class) * numClasses);
  206. numClasses = objc_getClassList(classes, numClasses);
  207. for (NSInteger classIndex = 0; classIndex < numClasses; ++classIndex) {
  208. Class class = classes[classIndex];
  209. if (class == [FLEXNetworkObserver class]) {
  210. continue;
  211. }
  212. // Use the runtime API rather than the methods on NSObject to avoid sending messages to
  213. // classes we're not interested in swizzling. Otherwise we hit +initialize on all classes.
  214. // NOTE: calling class_getInstanceMethod() DOES send +initialize to the class. That's why we iterate through the method list.
  215. unsigned int methodCount = 0;
  216. Method *methods = class_copyMethodList(class, &methodCount);
  217. BOOL matchingSelectorFound = NO;
  218. for (unsigned int methodIndex = 0; methodIndex < methodCount; methodIndex++) {
  219. for (int selectorIndex = 0; selectorIndex < numSelectors; ++selectorIndex) {
  220. if (method_getName(methods[methodIndex]) == selectors[selectorIndex]) {
  221. [self injectIntoDelegateClass:class];
  222. matchingSelectorFound = YES;
  223. break;
  224. }
  225. }
  226. if (matchingSelectorFound) {
  227. break;
  228. }
  229. }
  230. free(methods);
  231. }
  232. free(classes);
  233. }
  234. [self injectIntoNSURLConnectionCancel];
  235. [self injectIntoNSURLSessionTaskResume];
  236. [self injectIntoNSURLConnectionAsynchronousClassMethod];
  237. [self injectIntoNSURLConnectionSynchronousClassMethod];
  238. [self injectIntoNSURLSessionAsyncDataAndDownloadTaskMethods];
  239. [self injectIntoNSURLSessionAsyncUploadTaskMethods];
  240. });
  241. }
  242. + (void)injectIntoDelegateClass:(Class)cls
  243. {
  244. // Connections
  245. [self injectWillSendRequestIntoDelegateClass:cls];
  246. [self injectDidReceiveDataIntoDelegateClass:cls];
  247. [self injectDidReceiveResponseIntoDelegateClass:cls];
  248. [self injectDidFinishLoadingIntoDelegateClass:cls];
  249. [self injectDidFailWithErrorIntoDelegateClass:cls];
  250. // Sessions
  251. [self injectTaskWillPerformHTTPRedirectionIntoDelegateClass:cls];
  252. [self injectTaskDidReceiveDataIntoDelegateClass:cls];
  253. [self injectTaskDidReceiveResponseIntoDelegateClass:cls];
  254. [self injectTaskDidCompleteWithErrorIntoDelegateClass:cls];
  255. [self injectRespondsToSelectorIntoDelegateClass:cls];
  256. // Data tasks
  257. [self injectDataTaskDidBecomeDownloadTaskIntoDelegateClass:cls];
  258. // Download tasks
  259. [self injectDownloadTaskDidWriteDataIntoDelegateClass:cls];
  260. [self injectDownloadTaskDidFinishDownloadingIntoDelegateClass:cls];
  261. }
  262. + (void)injectIntoNSURLConnectionCancel
  263. {
  264. static dispatch_once_t onceToken;
  265. dispatch_once(&onceToken, ^{
  266. Class class = [NSURLConnection class];
  267. SEL selector = @selector(cancel);
  268. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  269. Method originalCancel = class_getInstanceMethod(class, selector);
  270. void (^swizzleBlock)(NSURLConnection *) = ^(NSURLConnection *slf) {
  271. [[FLEXNetworkObserver sharedObserver] connectionWillCancel:slf];
  272. ((void(*)(id, SEL))objc_msgSend)(slf, swizzledSelector);
  273. };
  274. IMP implementation = imp_implementationWithBlock(swizzleBlock);
  275. class_addMethod(class, swizzledSelector, implementation, method_getTypeEncoding(originalCancel));
  276. Method newCancel = class_getInstanceMethod(class, swizzledSelector);
  277. method_exchangeImplementations(originalCancel, newCancel);
  278. });
  279. }
  280. + (void)injectIntoNSURLSessionTaskResume
  281. {
  282. static dispatch_once_t onceToken;
  283. dispatch_once(&onceToken, ^{
  284. // In iOS 7 resume lives in __NSCFLocalSessionTask
  285. // In iOS 8 resume lives in NSURLSessionTask
  286. // In iOS 9 resume lives in __NSCFURLSessionTask
  287. Class class = Nil;
  288. if (![[NSProcessInfo processInfo] respondsToSelector:@selector(operatingSystemVersion)]) {
  289. class = NSClassFromString([@[@"__", @"NSC", @"FLocalS", @"ession", @"Task"] componentsJoinedByString:@""]);
  290. } else if ([[NSProcessInfo processInfo] operatingSystemVersion].majorVersion < 9) {
  291. class = [NSURLSessionTask class];
  292. } else {
  293. class = NSClassFromString([@[@"__", @"NSC", @"FURLS", @"ession", @"Task"] componentsJoinedByString:@""]);
  294. }
  295. SEL selector = @selector(resume);
  296. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  297. Method originalResume = class_getInstanceMethod(class, selector);
  298. void (^swizzleBlock)(NSURLSessionTask *) = ^(NSURLSessionTask *slf) {
  299. [[FLEXNetworkObserver sharedObserver] URLSessionTaskWillResume:slf];
  300. ((void(*)(id, SEL))objc_msgSend)(slf, swizzledSelector);
  301. };
  302. IMP implementation = imp_implementationWithBlock(swizzleBlock);
  303. class_addMethod(class, swizzledSelector, implementation, method_getTypeEncoding(originalResume));
  304. Method newResume = class_getInstanceMethod(class, swizzledSelector);
  305. method_exchangeImplementations(originalResume, newResume);
  306. });
  307. }
  308. + (void)injectIntoNSURLConnectionAsynchronousClassMethod
  309. {
  310. static dispatch_once_t onceToken;
  311. dispatch_once(&onceToken, ^{
  312. Class class = objc_getMetaClass(class_getName([NSURLConnection class]));
  313. SEL selector = @selector(sendAsynchronousRequest:queue:completionHandler:);
  314. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  315. typedef void (^NSURLConnectionAsyncCompletion)(NSURLResponse* response, NSData* data, NSError* connectionError);
  316. void (^asyncSwizzleBlock)(Class, NSURLRequest *, NSOperationQueue *, NSURLConnectionAsyncCompletion) = ^(Class slf, NSURLRequest *request, NSOperationQueue *queue, NSURLConnectionAsyncCompletion completion) {
  317. if ([FLEXNetworkObserver isEnabled]) {
  318. NSString *requestID = [self nextRequestID];
  319. [[FLEXNetworkRecorder defaultRecorder] recordRequestWillBeSentWithRequestID:requestID request:request redirectResponse:nil];
  320. NSString *mechanism = [self mechansimFromClassMethod:selector onClass:class];
  321. [[FLEXNetworkRecorder defaultRecorder] recordMechanism:mechanism forRequestID:requestID];
  322. NSURLConnectionAsyncCompletion completionWrapper = ^(NSURLResponse *response, NSData *data, NSError *connectionError) {
  323. [[FLEXNetworkRecorder defaultRecorder] recordResponseReceivedWithRequestID:requestID response:response];
  324. [[FLEXNetworkRecorder defaultRecorder] recordDataReceivedWithRequestID:requestID dataLength:[data length]];
  325. if (connectionError) {
  326. [[FLEXNetworkRecorder defaultRecorder] recordLoadingFailedWithRequestID:requestID error:connectionError];
  327. } else {
  328. [[FLEXNetworkRecorder defaultRecorder] recordLoadingFinishedWithRequestID:requestID responseBody:data];
  329. }
  330. // Call through to the original completion handler
  331. if (completion) {
  332. completion(response, data, connectionError);
  333. }
  334. };
  335. ((void(*)(id, SEL, id, id, id))objc_msgSend)(slf, swizzledSelector, request, queue, completionWrapper);
  336. } else {
  337. ((void(*)(id, SEL, id, id, id))objc_msgSend)(slf, swizzledSelector, request, queue, completion);
  338. }
  339. };
  340. [self replaceImplementationOfKnownSelector:selector onClass:class withBlock:asyncSwizzleBlock swizzledSelector:swizzledSelector];
  341. });
  342. }
  343. + (void)injectIntoNSURLConnectionSynchronousClassMethod
  344. {
  345. static dispatch_once_t onceToken;
  346. dispatch_once(&onceToken, ^{
  347. Class class = objc_getMetaClass(class_getName([NSURLConnection class]));
  348. SEL selector = @selector(sendSynchronousRequest:returningResponse:error:);
  349. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  350. NSData *(^syncSwizzleBlock)(Class, NSURLRequest *, NSURLResponse **, NSError **) = ^NSData *(Class slf, NSURLRequest *request, NSURLResponse **response, NSError **error) {
  351. NSData *data = nil;
  352. if ([FLEXNetworkObserver isEnabled]) {
  353. NSString *requestID = [self nextRequestID];
  354. [[FLEXNetworkRecorder defaultRecorder] recordRequestWillBeSentWithRequestID:requestID request:request redirectResponse:nil];
  355. NSString *mechanism = [self mechansimFromClassMethod:selector onClass:class];
  356. [[FLEXNetworkRecorder defaultRecorder] recordMechanism:mechanism forRequestID:requestID];
  357. NSError *temporaryError = nil;
  358. NSURLResponse *temporaryResponse = nil;
  359. data = ((id(*)(id, SEL, id, NSURLResponse **, NSError **))objc_msgSend)(slf, swizzledSelector, request, &temporaryResponse, &temporaryError);
  360. [[FLEXNetworkRecorder defaultRecorder] recordResponseReceivedWithRequestID:requestID response:temporaryResponse];
  361. [[FLEXNetworkRecorder defaultRecorder] recordDataReceivedWithRequestID:requestID dataLength:[data length]];
  362. if (temporaryError) {
  363. [[FLEXNetworkRecorder defaultRecorder] recordLoadingFailedWithRequestID:requestID error:temporaryError];
  364. } else {
  365. [[FLEXNetworkRecorder defaultRecorder] recordLoadingFinishedWithRequestID:requestID responseBody:data];
  366. }
  367. if (error) {
  368. *error = temporaryError;
  369. }
  370. if (response) {
  371. *response = temporaryResponse;
  372. }
  373. } else {
  374. data = ((id(*)(id, SEL, id, NSURLResponse **, NSError **))objc_msgSend)(slf, swizzledSelector, request, response, error);
  375. }
  376. return data;
  377. };
  378. [self replaceImplementationOfKnownSelector:selector onClass:class withBlock:syncSwizzleBlock swizzledSelector:swizzledSelector];
  379. });
  380. }
  381. + (void)injectIntoNSURLSessionAsyncDataAndDownloadTaskMethods
  382. {
  383. static dispatch_once_t onceToken;
  384. dispatch_once(&onceToken, ^{
  385. Class class = [NSURLSession class];
  386. // The method signatures here are close enough that we can use the same logic to inject into all of them.
  387. const SEL selectors[] = {
  388. @selector(dataTaskWithRequest:completionHandler:),
  389. @selector(dataTaskWithURL:completionHandler:),
  390. @selector(downloadTaskWithRequest:completionHandler:),
  391. @selector(downloadTaskWithResumeData:completionHandler:),
  392. @selector(downloadTaskWithURL:completionHandler:)
  393. };
  394. const int numSelectors = sizeof(selectors) / sizeof(SEL);
  395. for (int selectorIndex = 0; selectorIndex < numSelectors; selectorIndex++) {
  396. SEL selector = selectors[selectorIndex];
  397. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  398. if ([self instanceRespondsButDoesNotImplementSelector:selector class:class]) {
  399. // iOS 7 does not implement these methods on NSURLSession. We actually want to
  400. // swizzle __NSCFURLSession, which we can get from the class of the shared session
  401. class = [[NSURLSession sharedSession] class];
  402. }
  403. NSURLSessionTask *(^asyncDataOrDownloadSwizzleBlock)(Class, id, NSURLSessionAsyncCompletion) = ^NSURLSessionTask *(Class slf, id argument, NSURLSessionAsyncCompletion completion) {
  404. NSURLSessionTask *task = nil;
  405. // If completion block was not provided sender expect to receive delegated methods or does not
  406. // interested in callback at all. In this case we should just call original method implementation
  407. // with nil completion block.
  408. if ([FLEXNetworkObserver isEnabled] && completion) {
  409. NSString *requestID = [self nextRequestID];
  410. NSString *mechanism = [self mechansimFromClassMethod:selector onClass:class];
  411. NSURLSessionAsyncCompletion completionWrapper = [self asyncCompletionWrapperForRequestID:requestID mechanism:mechanism completion:completion];
  412. task = ((id(*)(id, SEL, id, id))objc_msgSend)(slf, swizzledSelector, argument, completionWrapper);
  413. [self setRequestID:requestID forConnectionOrTask:task];
  414. } else {
  415. task = ((id(*)(id, SEL, id, id))objc_msgSend)(slf, swizzledSelector, argument, completion);
  416. }
  417. return task;
  418. };
  419. [self replaceImplementationOfKnownSelector:selector onClass:class withBlock:asyncDataOrDownloadSwizzleBlock swizzledSelector:swizzledSelector];
  420. }
  421. });
  422. }
  423. + (void)injectIntoNSURLSessionAsyncUploadTaskMethods
  424. {
  425. static dispatch_once_t onceToken;
  426. dispatch_once(&onceToken, ^{
  427. Class class = [NSURLSession class];
  428. // The method signatures here are close enough that we can use the same logic to inject into both of them.
  429. // Note that they have 3 arguments, so we can't easily combine with the data and download method above.
  430. const SEL selectors[] = {
  431. @selector(uploadTaskWithRequest:fromData:completionHandler:),
  432. @selector(uploadTaskWithRequest:fromFile:completionHandler:)
  433. };
  434. const int numSelectors = sizeof(selectors) / sizeof(SEL);
  435. for (int selectorIndex = 0; selectorIndex < numSelectors; selectorIndex++) {
  436. SEL selector = selectors[selectorIndex];
  437. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  438. if ([self instanceRespondsButDoesNotImplementSelector:selector class:class]) {
  439. // iOS 7 does not implement these methods on NSURLSession. We actually want to
  440. // swizzle __NSCFURLSession, which we can get from the class of the shared session
  441. class = [[NSURLSession sharedSession] class];
  442. }
  443. NSURLSessionUploadTask *(^asyncUploadTaskSwizzleBlock)(Class, NSURLRequest *, id, NSURLSessionAsyncCompletion) = ^NSURLSessionUploadTask *(Class slf, NSURLRequest *request, id argument, NSURLSessionAsyncCompletion completion) {
  444. NSURLSessionUploadTask *task = nil;
  445. if ([FLEXNetworkObserver isEnabled]) {
  446. NSString *requestID = [self nextRequestID];
  447. NSString *mechanism = [self mechansimFromClassMethod:selector onClass:class];
  448. NSURLSessionAsyncCompletion completionWrapper = [self asyncCompletionWrapperForRequestID:requestID mechanism:mechanism completion:completion];
  449. task = ((id(*)(id, SEL, id, id, id))objc_msgSend)(slf, swizzledSelector, request, argument, completionWrapper);
  450. [self setRequestID:requestID forConnectionOrTask:task];
  451. } else {
  452. task = ((id(*)(id, SEL, id, id, id))objc_msgSend)(slf, swizzledSelector, request, argument, completion);
  453. }
  454. return task;
  455. };
  456. [self replaceImplementationOfKnownSelector:selector onClass:class withBlock:asyncUploadTaskSwizzleBlock swizzledSelector:swizzledSelector];
  457. }
  458. });
  459. }
  460. + (NSString *)mechansimFromClassMethod:(SEL)selector onClass:(Class)class
  461. {
  462. return [NSString stringWithFormat:@"+[%@ %@]", NSStringFromClass(class), NSStringFromSelector(selector)];
  463. }
  464. + (NSURLSessionAsyncCompletion)asyncCompletionWrapperForRequestID:(NSString *)requestID mechanism:(NSString *)mechanism completion:(NSURLSessionAsyncCompletion)completion
  465. {
  466. NSURLSessionAsyncCompletion completionWrapper = ^(id fileURLOrData, NSURLResponse *response, NSError *error) {
  467. [[FLEXNetworkRecorder defaultRecorder] recordMechanism:mechanism forRequestID:requestID];
  468. [[FLEXNetworkRecorder defaultRecorder] recordResponseReceivedWithRequestID:requestID response:response];
  469. NSData *data = nil;
  470. if ([fileURLOrData isKindOfClass:[NSURL class]]) {
  471. data = [NSData dataWithContentsOfURL:fileURLOrData];
  472. } else if ([fileURLOrData isKindOfClass:[NSData class]]) {
  473. data = fileURLOrData;
  474. }
  475. [[FLEXNetworkRecorder defaultRecorder] recordDataReceivedWithRequestID:requestID dataLength:[data length]];
  476. if (error) {
  477. [[FLEXNetworkRecorder defaultRecorder] recordLoadingFailedWithRequestID:requestID error:error];
  478. } else {
  479. [[FLEXNetworkRecorder defaultRecorder] recordLoadingFinishedWithRequestID:requestID responseBody:data];
  480. }
  481. // Call through to the original completion handler
  482. if (completion) {
  483. completion(fileURLOrData, response, error);
  484. }
  485. };
  486. return completionWrapper;
  487. }
  488. + (void)injectWillSendRequestIntoDelegateClass:(Class)cls
  489. {
  490. SEL selector = @selector(connection:willSendRequest:redirectResponse:);
  491. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  492. Protocol *protocol = @protocol(NSURLConnectionDataDelegate);
  493. if (!protocol) {
  494. protocol = @protocol(NSURLConnectionDelegate);
  495. }
  496. struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES);
  497. typedef NSURLRequest *(^NSURLConnectionWillSendRequestBlock)(id <NSURLConnectionDelegate> slf, NSURLConnection *connection, NSURLRequest *request, NSURLResponse *response);
  498. NSURLConnectionWillSendRequestBlock undefinedBlock = ^NSURLRequest *(id <NSURLConnectionDelegate> slf, NSURLConnection *connection, NSURLRequest *request, NSURLResponse *response) {
  499. [[FLEXNetworkObserver sharedObserver] connection:connection willSendRequest:request redirectResponse:response delegate:slf];
  500. return request;
  501. };
  502. NSURLConnectionWillSendRequestBlock implementationBlock = ^NSURLRequest *(id <NSURLConnectionDelegate> slf, NSURLConnection *connection, NSURLRequest *request, NSURLResponse *response) {
  503. __block NSURLRequest *returnValue = nil;
  504. [self sniffWithoutDuplicationForObject:connection selector:selector sniffingBlock:^{
  505. undefinedBlock(slf, connection, request, response);
  506. } originalImplementationBlock:^{
  507. returnValue = ((id(*)(id, SEL, id, id, id))objc_msgSend)(slf, swizzledSelector, connection, request, response);
  508. }];
  509. return returnValue;
  510. };
  511. [self replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription implementationBlock:implementationBlock undefinedBlock:undefinedBlock];
  512. }
  513. + (void)injectDidReceiveResponseIntoDelegateClass:(Class)cls
  514. {
  515. SEL selector = @selector(connection:didReceiveResponse:);
  516. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  517. Protocol *protocol = @protocol(NSURLConnectionDataDelegate);
  518. if (!protocol) {
  519. protocol = @protocol(NSURLConnectionDelegate);
  520. }
  521. struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES);
  522. typedef void (^NSURLConnectionDidReceiveResponseBlock)(id <NSURLConnectionDelegate> slf, NSURLConnection *connection, NSURLResponse *response);
  523. NSURLConnectionDidReceiveResponseBlock undefinedBlock = ^(id <NSURLConnectionDelegate> slf, NSURLConnection *connection, NSURLResponse *response) {
  524. [[FLEXNetworkObserver sharedObserver] connection:connection didReceiveResponse:response delegate:slf];
  525. };
  526. NSURLConnectionDidReceiveResponseBlock implementationBlock = ^(id <NSURLConnectionDelegate> slf, NSURLConnection *connection, NSURLResponse *response) {
  527. [self sniffWithoutDuplicationForObject:connection selector:selector sniffingBlock:^{
  528. undefinedBlock(slf, connection, response);
  529. } originalImplementationBlock:^{
  530. ((void(*)(id, SEL, id, id))objc_msgSend)(slf, swizzledSelector, connection, response);
  531. }];
  532. };
  533. [self replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription implementationBlock:implementationBlock undefinedBlock:undefinedBlock];
  534. }
  535. + (void)injectDidReceiveDataIntoDelegateClass:(Class)cls
  536. {
  537. SEL selector = @selector(connection:didReceiveData:);
  538. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  539. Protocol *protocol = @protocol(NSURLConnectionDataDelegate);
  540. if (!protocol) {
  541. protocol = @protocol(NSURLConnectionDelegate);
  542. }
  543. struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES);
  544. typedef void (^NSURLConnectionDidReceiveDataBlock)(id <NSURLConnectionDelegate> slf, NSURLConnection *connection, NSData *data);
  545. NSURLConnectionDidReceiveDataBlock undefinedBlock = ^(id <NSURLConnectionDelegate> slf, NSURLConnection *connection, NSData *data) {
  546. [[FLEXNetworkObserver sharedObserver] connection:connection didReceiveData:data delegate:slf];
  547. };
  548. NSURLConnectionDidReceiveDataBlock implementationBlock = ^(id <NSURLConnectionDelegate> slf, NSURLConnection *connection, NSData *data) {
  549. [self sniffWithoutDuplicationForObject:connection selector:selector sniffingBlock:^{
  550. undefinedBlock(slf, connection, data);
  551. } originalImplementationBlock:^{
  552. ((void(*)(id, SEL, id, id))objc_msgSend)(slf, swizzledSelector, connection, data);
  553. }];
  554. };
  555. [self replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription implementationBlock:implementationBlock undefinedBlock:undefinedBlock];
  556. }
  557. + (void)injectDidFinishLoadingIntoDelegateClass:(Class)cls
  558. {
  559. SEL selector = @selector(connectionDidFinishLoading:);
  560. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  561. Protocol *protocol = @protocol(NSURLConnectionDataDelegate);
  562. if (!protocol) {
  563. protocol = @protocol(NSURLConnectionDelegate);
  564. }
  565. struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES);
  566. typedef void (^NSURLConnectionDidFinishLoadingBlock)(id <NSURLConnectionDelegate> slf, NSURLConnection *connection);
  567. NSURLConnectionDidFinishLoadingBlock undefinedBlock = ^(id <NSURLConnectionDelegate> slf, NSURLConnection *connection) {
  568. [[FLEXNetworkObserver sharedObserver] connectionDidFinishLoading:connection delegate:slf];
  569. };
  570. NSURLConnectionDidFinishLoadingBlock implementationBlock = ^(id <NSURLConnectionDelegate> slf, NSURLConnection *connection) {
  571. [self sniffWithoutDuplicationForObject:connection selector:selector sniffingBlock:^{
  572. undefinedBlock(slf, connection);
  573. } originalImplementationBlock:^{
  574. ((void(*)(id, SEL, id))objc_msgSend)(slf, swizzledSelector, connection);
  575. }];
  576. };
  577. [self replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription implementationBlock:implementationBlock undefinedBlock:undefinedBlock];
  578. }
  579. + (void)injectDidFailWithErrorIntoDelegateClass:(Class)cls
  580. {
  581. SEL selector = @selector(connection:didFailWithError:);
  582. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  583. Protocol *protocol = @protocol(NSURLConnectionDelegate);
  584. struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES);
  585. typedef void (^NSURLConnectionDidFailWithErrorBlock)(id <NSURLConnectionDelegate> slf, NSURLConnection *connection, NSError *error);
  586. NSURLConnectionDidFailWithErrorBlock undefinedBlock = ^(id <NSURLConnectionDelegate> slf, NSURLConnection *connection, NSError *error) {
  587. [[FLEXNetworkObserver sharedObserver] connection:connection didFailWithError:error delegate:slf];
  588. };
  589. NSURLConnectionDidFailWithErrorBlock implementationBlock = ^(id <NSURLConnectionDelegate> slf, NSURLConnection *connection, NSError *error) {
  590. [self sniffWithoutDuplicationForObject:connection selector:selector sniffingBlock:^{
  591. undefinedBlock(slf, connection, error);
  592. } originalImplementationBlock:^{
  593. ((void(*)(id, SEL, id, id))objc_msgSend)(slf, swizzledSelector, connection, error);
  594. }];
  595. };
  596. [self replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription implementationBlock:implementationBlock undefinedBlock:undefinedBlock];
  597. }
  598. + (void)injectTaskWillPerformHTTPRedirectionIntoDelegateClass:(Class)cls
  599. {
  600. SEL selector = @selector(URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:);
  601. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  602. Protocol *protocol = @protocol(NSURLSessionTaskDelegate);
  603. struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES);
  604. typedef void (^NSURLSessionWillPerformHTTPRedirectionBlock)(id <NSURLSessionTaskDelegate> slf, NSURLSession *session, NSURLSessionTask *task, NSHTTPURLResponse *response, NSURLRequest *newRequest, void(^completionHandler)(NSURLRequest *));
  605. NSURLSessionWillPerformHTTPRedirectionBlock undefinedBlock = ^(id <NSURLSessionTaskDelegate> slf, NSURLSession *session, NSURLSessionTask *task, NSHTTPURLResponse *response, NSURLRequest *newRequest, void(^completionHandler)(NSURLRequest *)) {
  606. [[FLEXNetworkObserver sharedObserver] URLSession:session task:task willPerformHTTPRedirection:response newRequest:newRequest completionHandler:completionHandler delegate:slf];
  607. };
  608. NSURLSessionWillPerformHTTPRedirectionBlock implementationBlock = ^(id <NSURLSessionTaskDelegate> slf, NSURLSession *session, NSURLSessionTask *task, NSHTTPURLResponse *response, NSURLRequest *newRequest, void(^completionHandler)(NSURLRequest *)) {
  609. [self sniffWithoutDuplicationForObject:session selector:selector sniffingBlock:^{
  610. undefinedBlock(slf, session, task, response, newRequest, completionHandler);
  611. } originalImplementationBlock:^{
  612. ((id(*)(id, SEL, id, id, id, id, void(^)()))objc_msgSend)(slf, swizzledSelector, session, task, response, newRequest, completionHandler);
  613. }];
  614. };
  615. [self replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription implementationBlock:implementationBlock undefinedBlock:undefinedBlock];
  616. }
  617. + (void)injectTaskDidReceiveDataIntoDelegateClass:(Class)cls
  618. {
  619. SEL selector = @selector(URLSession:dataTask:didReceiveData:);
  620. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  621. Protocol *protocol = @protocol(NSURLSessionDataDelegate);
  622. struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES);
  623. typedef void (^NSURLSessionDidReceiveDataBlock)(id <NSURLSessionDataDelegate> slf, NSURLSession *session, NSURLSessionDataTask *dataTask, NSData *data);
  624. NSURLSessionDidReceiveDataBlock undefinedBlock = ^(id <NSURLSessionDataDelegate> slf, NSURLSession *session, NSURLSessionDataTask *dataTask, NSData *data) {
  625. [[FLEXNetworkObserver sharedObserver] URLSession:session dataTask:dataTask didReceiveData:data delegate:slf];
  626. };
  627. NSURLSessionDidReceiveDataBlock implementationBlock = ^(id <NSURLSessionDataDelegate> slf, NSURLSession *session, NSURLSessionDataTask *dataTask, NSData *data) {
  628. [self sniffWithoutDuplicationForObject:session selector:selector sniffingBlock:^{
  629. undefinedBlock(slf, session, dataTask, data);
  630. } originalImplementationBlock:^{
  631. ((void(*)(id, SEL, id, id, id))objc_msgSend)(slf, swizzledSelector, session, dataTask, data);
  632. }];
  633. };
  634. [self replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription implementationBlock:implementationBlock undefinedBlock:undefinedBlock];
  635. }
  636. + (void)injectDataTaskDidBecomeDownloadTaskIntoDelegateClass:(Class)cls
  637. {
  638. SEL selector = @selector(URLSession:dataTask:didBecomeDownloadTask:);
  639. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  640. Protocol *protocol = @protocol(NSURLSessionDataDelegate);
  641. struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES);
  642. typedef void (^NSURLSessionDidBecomeDownloadTaskBlock)(id <NSURLSessionDataDelegate> slf, NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLSessionDownloadTask *downloadTask);
  643. NSURLSessionDidBecomeDownloadTaskBlock undefinedBlock = ^(id <NSURLSessionDataDelegate> slf, NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLSessionDownloadTask *downloadTask) {
  644. [[FLEXNetworkObserver sharedObserver] URLSession:session dataTask:dataTask didBecomeDownloadTask:downloadTask delegate:slf];
  645. };
  646. NSURLSessionDidBecomeDownloadTaskBlock implementationBlock = ^(id <NSURLSessionDataDelegate> slf, NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLSessionDownloadTask *downloadTask) {
  647. [self sniffWithoutDuplicationForObject:session selector:selector sniffingBlock:^{
  648. undefinedBlock(slf, session, dataTask, downloadTask);
  649. } originalImplementationBlock:^{
  650. ((void(*)(id, SEL, id, id, id))objc_msgSend)(slf, swizzledSelector, session, dataTask, downloadTask);
  651. }];
  652. };
  653. [self replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription implementationBlock:implementationBlock undefinedBlock:undefinedBlock];
  654. }
  655. + (void)injectTaskDidReceiveResponseIntoDelegateClass:(Class)cls
  656. {
  657. SEL selector = @selector(URLSession:dataTask:didReceiveResponse:completionHandler:);
  658. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  659. Protocol *protocol = @protocol(NSURLSessionDataDelegate);
  660. struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES);
  661. typedef void (^NSURLSessionDidReceiveResponseBlock)(id <NSURLSessionDelegate> slf, NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLResponse *response, void(^completionHandler)(NSURLSessionResponseDisposition disposition));
  662. NSURLSessionDidReceiveResponseBlock undefinedBlock = ^(id <NSURLSessionDelegate> slf, NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLResponse *response, void(^completionHandler)(NSURLSessionResponseDisposition disposition)) {
  663. [[FLEXNetworkObserver sharedObserver] URLSession:session dataTask:dataTask didReceiveResponse:response completionHandler:completionHandler delegate:slf];
  664. };
  665. NSURLSessionDidReceiveResponseBlock implementationBlock = ^(id <NSURLSessionDelegate> slf, NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLResponse *response, void(^completionHandler)(NSURLSessionResponseDisposition disposition)) {
  666. [self sniffWithoutDuplicationForObject:session selector:selector sniffingBlock:^{
  667. undefinedBlock(slf, session, dataTask, response, completionHandler);
  668. } originalImplementationBlock:^{
  669. ((void(*)(id, SEL, id, id, id, void(^)()))objc_msgSend)(slf, swizzledSelector, session, dataTask, response, completionHandler);
  670. }];
  671. };
  672. [self replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription implementationBlock:implementationBlock undefinedBlock:undefinedBlock];
  673. }
  674. + (void)injectTaskDidCompleteWithErrorIntoDelegateClass:(Class)cls
  675. {
  676. SEL selector = @selector(URLSession:task:didCompleteWithError:);
  677. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  678. Protocol *protocol = @protocol(NSURLSessionTaskDelegate);
  679. struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES);
  680. typedef void (^NSURLSessionTaskDidCompleteWithErrorBlock)(id <NSURLSessionTaskDelegate> slf, NSURLSession *session, NSURLSessionTask *task, NSError *error);
  681. NSURLSessionTaskDidCompleteWithErrorBlock undefinedBlock = ^(id <NSURLSessionTaskDelegate> slf, NSURLSession *session, NSURLSessionTask *task, NSError *error) {
  682. [[FLEXNetworkObserver sharedObserver] URLSession:session task:task didCompleteWithError:error delegate:slf];
  683. };
  684. NSURLSessionTaskDidCompleteWithErrorBlock implementationBlock = ^(id <NSURLSessionTaskDelegate> slf, NSURLSession *session, NSURLSessionTask *task, NSError *error) {
  685. [self sniffWithoutDuplicationForObject:session selector:selector sniffingBlock:^{
  686. undefinedBlock(slf, session, task, error);
  687. } originalImplementationBlock:^{
  688. ((void(*)(id, SEL, id, id, id))objc_msgSend)(slf, swizzledSelector, session, task, error);
  689. }];
  690. };
  691. [self replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription implementationBlock:implementationBlock undefinedBlock:undefinedBlock];
  692. }
  693. // Used for overriding AFNetworking behavior
  694. + (void)injectRespondsToSelectorIntoDelegateClass:(Class)cls
  695. {
  696. SEL selector = @selector(respondsToSelector:);
  697. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  698. //Protocol *protocol = @protocol(NSURLSessionTaskDelegate);
  699. Method method = class_getInstanceMethod(cls, selector);
  700. struct objc_method_description methodDescription = *method_getDescription(method);
  701. BOOL (^undefinedBlock)(id <NSURLSessionTaskDelegate>, SEL) = ^(id slf, SEL sel) {
  702. return YES;
  703. };
  704. BOOL (^implementationBlock)(id <NSURLSessionTaskDelegate>, SEL) = ^(id <NSURLSessionTaskDelegate> slf, SEL sel) {
  705. if (sel == @selector(URLSession:dataTask:didReceiveResponse:completionHandler:)) {
  706. return undefinedBlock(slf, sel);
  707. }
  708. return ((BOOL(*)(id, SEL, SEL))objc_msgSend)(slf, swizzledSelector, sel);
  709. };
  710. [self replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription implementationBlock:implementationBlock undefinedBlock:undefinedBlock];
  711. }
  712. + (void)injectDownloadTaskDidFinishDownloadingIntoDelegateClass:(Class)cls
  713. {
  714. SEL selector = @selector(URLSession:downloadTask:didFinishDownloadingToURL:);
  715. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  716. Protocol *protocol = @protocol(NSURLSessionDownloadDelegate);
  717. struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES);
  718. typedef void (^NSURLSessionDownloadTaskDidFinishDownloadingBlock)(id <NSURLSessionTaskDelegate> slf, NSURLSession *session, NSURLSessionDownloadTask *task, NSURL *location);
  719. NSURLSessionDownloadTaskDidFinishDownloadingBlock undefinedBlock = ^(id <NSURLSessionTaskDelegate> slf, NSURLSession *session, NSURLSessionDownloadTask *task, NSURL *location) {
  720. NSData *data = [NSData dataWithContentsOfFile:location.relativePath];
  721. [[FLEXNetworkObserver sharedObserver] URLSession:session task:task didFinishDownloadingToURL:location data:data delegate:slf];
  722. };
  723. NSURLSessionDownloadTaskDidFinishDownloadingBlock implementationBlock = ^(id <NSURLSessionTaskDelegate> slf, NSURLSession *session, NSURLSessionDownloadTask *task, NSURL *location) {
  724. [self sniffWithoutDuplicationForObject:session selector:selector sniffingBlock:^{
  725. undefinedBlock(slf, session, task, location);
  726. } originalImplementationBlock:^{
  727. ((void(*)(id, SEL, id, id, id))objc_msgSend)(slf, swizzledSelector, session, task, location);
  728. }];
  729. };
  730. [self replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription implementationBlock:implementationBlock undefinedBlock:undefinedBlock];
  731. }
  732. + (void)injectDownloadTaskDidWriteDataIntoDelegateClass:(Class)cls
  733. {
  734. SEL selector = @selector(URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:);
  735. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  736. Protocol *protocol = @protocol(NSURLSessionDownloadDelegate);
  737. struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES);
  738. typedef void (^NSURLSessionDownloadTaskDidWriteDataBlock)(id <NSURLSessionTaskDelegate> slf, NSURLSession *session, NSURLSessionDownloadTask *task, int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite);
  739. NSURLSessionDownloadTaskDidWriteDataBlock undefinedBlock = ^(id <NSURLSessionTaskDelegate> slf, NSURLSession *session, NSURLSessionDownloadTask *task, int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite) {
  740. [[FLEXNetworkObserver sharedObserver] URLSession:session downloadTask:task didWriteData:bytesWritten totalBytesWritten:totalBytesWritten totalBytesExpectedToWrite:totalBytesExpectedToWrite delegate:slf];
  741. };
  742. NSURLSessionDownloadTaskDidWriteDataBlock implementationBlock = ^(id <NSURLSessionTaskDelegate> slf, NSURLSession *session, NSURLSessionDownloadTask *task, int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite) {
  743. [self sniffWithoutDuplicationForObject:session selector:selector sniffingBlock:^{
  744. undefinedBlock(slf, session, task, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite);
  745. } originalImplementationBlock:^{
  746. ((void(*)(id, SEL, id, id, int64_t, int64_t, int64_t))objc_msgSend)(slf, swizzledSelector, session, task, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite);
  747. }];
  748. };
  749. [self replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription implementationBlock:implementationBlock undefinedBlock:undefinedBlock];
  750. }
  751. static char const * const kFLEXRequestIDKey = "kFLEXRequestIDKey";
  752. + (NSString *)requestIDForConnectionOrTask:(id)connectionOrTask
  753. {
  754. NSString *requestID = objc_getAssociatedObject(connectionOrTask, kFLEXRequestIDKey);
  755. if (!requestID) {
  756. requestID = [self nextRequestID];
  757. [self setRequestID:requestID forConnectionOrTask:connectionOrTask];
  758. }
  759. return requestID;
  760. }
  761. + (void)setRequestID:(NSString *)requestID forConnectionOrTask:(id)connectionOrTask
  762. {
  763. objc_setAssociatedObject(connectionOrTask, kFLEXRequestIDKey, requestID, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
  764. }
  765. #pragma mark - Initialization
  766. - (id)init
  767. {
  768. self = [super init];
  769. if (self) {
  770. self.requestStatesForRequestIDs = [[NSMutableDictionary alloc] init];
  771. self.queue = dispatch_queue_create("com.flex.FLEXNetworkObserver", DISPATCH_QUEUE_SERIAL);
  772. }
  773. return self;
  774. }
  775. #pragma mark - Private Methods
  776. - (void)performBlock:(dispatch_block_t)block
  777. {
  778. if (self.isEnabled) {
  779. dispatch_async(_queue, block);
  780. }
  781. }
  782. - (FLEXInternalRequestState *)requestStateForRequestID:(NSString *)requestID
  783. {
  784. FLEXInternalRequestState *requestState = [self.requestStatesForRequestIDs objectForKey:requestID];
  785. if (!requestState) {
  786. requestState = [[FLEXInternalRequestState alloc] init];
  787. [self.requestStatesForRequestIDs setObject:requestState forKey:requestID];
  788. }
  789. return requestState;
  790. }
  791. - (void)removeRequestStateForRequestID:(NSString *)requestID
  792. {
  793. [self.requestStatesForRequestIDs removeObjectForKey:requestID];
  794. }
  795. @end
  796. @implementation FLEXNetworkObserver (NSURLConnectionHelpers)
  797. - (void)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response delegate:(id<NSURLConnectionDelegate>)delegate
  798. {
  799. [self performBlock:^{
  800. NSString *requestID = [[self class] requestIDForConnectionOrTask:connection];
  801. FLEXInternalRequestState *requestState = [self requestStateForRequestID:requestID];
  802. requestState.request = request;
  803. [[FLEXNetworkRecorder defaultRecorder] recordRequestWillBeSentWithRequestID:requestID request:request redirectResponse:response];
  804. NSString *mechanism = [NSString stringWithFormat:@"NSURLConnection (delegate: %@)", [delegate class]];
  805. [[FLEXNetworkRecorder defaultRecorder] recordMechanism:mechanism forRequestID:requestID];
  806. }];
  807. }
  808. - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response delegate:(id<NSURLConnectionDelegate>)delegate
  809. {
  810. [self performBlock:^{
  811. NSString *requestID = [[self class] requestIDForConnectionOrTask:connection];
  812. FLEXInternalRequestState *requestState = [self requestStateForRequestID:requestID];
  813. NSMutableData *dataAccumulator = nil;
  814. if (response.expectedContentLength < 0) {
  815. dataAccumulator = [[NSMutableData alloc] init];
  816. } else {
  817. dataAccumulator = [[NSMutableData alloc] initWithCapacity:(NSUInteger)response.expectedContentLength];
  818. }
  819. requestState.dataAccumulator = dataAccumulator;
  820. [[FLEXNetworkRecorder defaultRecorder] recordResponseReceivedWithRequestID:requestID response:response];
  821. }];
  822. }
  823. - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data delegate:(id<NSURLConnectionDelegate>)delegate
  824. {
  825. // Just to be safe since we're doing this async
  826. data = [data copy];
  827. [self performBlock:^{
  828. NSString *requestID = [[self class] requestIDForConnectionOrTask:connection];
  829. FLEXInternalRequestState *requestState = [self requestStateForRequestID:requestID];
  830. [requestState.dataAccumulator appendData:data];
  831. [[FLEXNetworkRecorder defaultRecorder] recordDataReceivedWithRequestID:requestID dataLength:data.length];
  832. }];
  833. }
  834. - (void)connectionDidFinishLoading:(NSURLConnection *)connection delegate:(id<NSURLConnectionDelegate>)delegate
  835. {
  836. [self performBlock:^{
  837. NSString *requestID = [[self class] requestIDForConnectionOrTask:connection];
  838. FLEXInternalRequestState *requestState = [self requestStateForRequestID:requestID];
  839. [[FLEXNetworkRecorder defaultRecorder] recordLoadingFinishedWithRequestID:requestID responseBody:requestState.dataAccumulator];
  840. [self removeRequestStateForRequestID:requestID];
  841. }];
  842. }
  843. - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error delegate:(id<NSURLConnectionDelegate>)delegate
  844. {
  845. [self performBlock:^{
  846. NSString *requestID = [[self class] requestIDForConnectionOrTask:connection];
  847. FLEXInternalRequestState *requestState = [self requestStateForRequestID:requestID];
  848. // Cancellations can occur prior to the willSendRequest:... NSURLConnection delegate call.
  849. // These are pretty common and clutter up the logs. Only record the failure if the recorder already knows about the request through willSendRequest:...
  850. if (requestState.request) {
  851. [[FLEXNetworkRecorder defaultRecorder] recordLoadingFailedWithRequestID:requestID error:error];
  852. }
  853. [self removeRequestStateForRequestID:requestID];
  854. }];
  855. }
  856. - (void)connectionWillCancel:(NSURLConnection *)connection
  857. {
  858. [self performBlock:^{
  859. // Mimic the behavior of NSURLSession which is to create an error on cancellation.
  860. NSDictionary *userInfo = @{ NSLocalizedDescriptionKey : @"cancelled" };
  861. NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorCancelled userInfo:userInfo];
  862. [self connection:connection didFailWithError:error delegate:nil];
  863. }];
  864. }
  865. @end
  866. @implementation FLEXNetworkObserver (NSURLSessionTaskHelpers)
  867. - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task willPerformHTTPRedirection:(NSHTTPURLResponse *)response newRequest:(NSURLRequest *)request completionHandler:(void (^)(NSURLRequest *))completionHandler delegate:(id<NSURLSessionDelegate>)delegate
  868. {
  869. [self performBlock:^{
  870. NSString *requestID = [[self class] requestIDForConnectionOrTask:task];
  871. [[FLEXNetworkRecorder defaultRecorder] recordRequestWillBeSentWithRequestID:requestID request:request redirectResponse:response];
  872. }];
  873. }
  874. - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler delegate:(id<NSURLSessionDelegate>)delegate
  875. {
  876. [self performBlock:^{
  877. NSString *requestID = [[self class] requestIDForConnectionOrTask:dataTask];
  878. FLEXInternalRequestState *requestState = [self requestStateForRequestID:requestID];
  879. NSMutableData *dataAccumulator = nil;
  880. if (response.expectedContentLength < 0) {
  881. dataAccumulator = [[NSMutableData alloc] init];
  882. } else {
  883. dataAccumulator = [[NSMutableData alloc] initWithCapacity:(NSUInteger)response.expectedContentLength];
  884. }
  885. requestState.dataAccumulator = dataAccumulator;
  886. NSString *requestMechanism = [NSString stringWithFormat:@"NSURLSessionDataTask (delegate: %@)", [delegate class]];
  887. [[FLEXNetworkRecorder defaultRecorder] recordMechanism:requestMechanism forRequestID:requestID];
  888. [[FLEXNetworkRecorder defaultRecorder] recordResponseReceivedWithRequestID:requestID response:response];
  889. }];
  890. }
  891. - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didBecomeDownloadTask:(NSURLSessionDownloadTask *)downloadTask delegate:(id<NSURLSessionDelegate>)delegate
  892. {
  893. [self performBlock:^{
  894. // By setting the request ID of the download task to match the data task,
  895. // it can pick up where the data task left off.
  896. NSString *requestID = [[self class] requestIDForConnectionOrTask:dataTask];
  897. [[self class] setRequestID:requestID forConnectionOrTask:downloadTask];
  898. }];
  899. }
  900. - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data delegate:(id<NSURLSessionDelegate>)delegate
  901. {
  902. // Just to be safe since we're doing this async
  903. data = [data copy];
  904. [self performBlock:^{
  905. NSString *requestID = [[self class] requestIDForConnectionOrTask:dataTask];
  906. FLEXInternalRequestState *requestState = [self requestStateForRequestID:requestID];
  907. [requestState.dataAccumulator appendData:data];
  908. [[FLEXNetworkRecorder defaultRecorder] recordDataReceivedWithRequestID:requestID dataLength:data.length];
  909. }];
  910. }
  911. - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error delegate:(id<NSURLSessionDelegate>)delegate
  912. {
  913. [self performBlock:^{
  914. NSString *requestID = [[self class] requestIDForConnectionOrTask:task];
  915. FLEXInternalRequestState *requestState = [self requestStateForRequestID:requestID];
  916. if (error) {
  917. [[FLEXNetworkRecorder defaultRecorder] recordLoadingFailedWithRequestID:requestID error:error];
  918. } else {
  919. [[FLEXNetworkRecorder defaultRecorder] recordLoadingFinishedWithRequestID:requestID responseBody:requestState.dataAccumulator];
  920. }
  921. [self removeRequestStateForRequestID:requestID];
  922. }];
  923. }
  924. - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite delegate:(id<NSURLSessionDelegate>)delegate
  925. {
  926. [self performBlock:^{
  927. NSString *requestID = [[self class] requestIDForConnectionOrTask:downloadTask];
  928. FLEXInternalRequestState *requestState = [self requestStateForRequestID:requestID];
  929. if (!requestState.dataAccumulator) {
  930. NSUInteger unsignedBytesExpectedToWrite = totalBytesExpectedToWrite > 0 ? (NSUInteger)totalBytesExpectedToWrite : 0;
  931. requestState.dataAccumulator = [[NSMutableData alloc] initWithCapacity:unsignedBytesExpectedToWrite];
  932. [[FLEXNetworkRecorder defaultRecorder] recordResponseReceivedWithRequestID:requestID response:downloadTask.response];
  933. NSString *requestMechanism = [NSString stringWithFormat:@"NSURLSessionDownloadTask (delegate: %@)", [delegate class]];
  934. [[FLEXNetworkRecorder defaultRecorder] recordMechanism:requestMechanism forRequestID:requestID];
  935. }
  936. [[FLEXNetworkRecorder defaultRecorder] recordDataReceivedWithRequestID:requestID dataLength:bytesWritten];
  937. }];
  938. }
  939. - (void)URLSession:(NSURLSession *)session task:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location data:(NSData *)data delegate:(id<NSURLSessionDelegate>)delegate
  940. {
  941. data = [data copy];
  942. [self performBlock:^{
  943. NSString *requestID = [[self class] requestIDForConnectionOrTask:downloadTask];
  944. FLEXInternalRequestState *requestState = [self requestStateForRequestID:requestID];
  945. [requestState.dataAccumulator appendData:data];
  946. }];
  947. }
  948. - (void)URLSessionTaskWillResume:(NSURLSessionTask *)task
  949. {
  950. // Since resume can be called multiple times on the same task, only treat the first resume as
  951. // the equivalent to connection:willSendRequest:...
  952. [self performBlock:^{
  953. NSString *requestID = [[self class] requestIDForConnectionOrTask:task];
  954. FLEXInternalRequestState *requestState = [self requestStateForRequestID:requestID];
  955. if (!requestState.request) {
  956. requestState.request = task.currentRequest;
  957. [[FLEXNetworkRecorder defaultRecorder] recordRequestWillBeSentWithRequestID:requestID request:task.currentRequest redirectResponse:nil];
  958. }
  959. }];
  960. }
  961. @end