FLEXNetworkObserver.m 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192
  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. Class class = [NSURLSessionTask class];
  285. SEL selector = @selector(resume);
  286. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  287. if ([self instanceRespondsButDoesNotImplementSelector:selector class:class]) {
  288. // Dummy NSURLSessionTask to get the actual class, needed for iOS 7 (__NSCFURLSessionTask)
  289. class = [[[NSURLSession sharedSession] dataTaskWithURL:[NSURL URLWithString:@"about:blank"]] superclass];
  290. }
  291. Method originalResume = class_getInstanceMethod(class, selector);
  292. void (^swizzleBlock)(NSURLSessionTask *) = ^(NSURLSessionTask *slf) {
  293. [[FLEXNetworkObserver sharedObserver] URLSessionTaskWillResume:slf];
  294. ((void(*)(id, SEL))objc_msgSend)(slf, swizzledSelector);
  295. };
  296. IMP implementation = imp_implementationWithBlock(swizzleBlock);
  297. class_addMethod(class, swizzledSelector, implementation, method_getTypeEncoding(originalResume));
  298. Method newResume = class_getInstanceMethod(class, swizzledSelector);
  299. method_exchangeImplementations(originalResume, newResume);
  300. });
  301. }
  302. + (void)injectIntoNSURLConnectionAsynchronousClassMethod
  303. {
  304. static dispatch_once_t onceToken;
  305. dispatch_once(&onceToken, ^{
  306. Class class = objc_getMetaClass(class_getName([NSURLConnection class]));
  307. SEL selector = @selector(sendAsynchronousRequest:queue:completionHandler:);
  308. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  309. typedef void (^NSURLConnectionAsyncCompletion)(NSURLResponse* response, NSData* data, NSError* connectionError);
  310. void (^asyncSwizzleBlock)(Class, NSURLRequest *, NSOperationQueue *, NSURLConnectionAsyncCompletion) = ^(Class slf, NSURLRequest *request, NSOperationQueue *queue, NSURLConnectionAsyncCompletion completion) {
  311. if ([FLEXNetworkObserver isEnabled]) {
  312. NSString *requestID = [self nextRequestID];
  313. [[FLEXNetworkRecorder defaultRecorder] recordRequestWillBeSentWithRequestID:requestID request:request redirectResponse:nil];
  314. NSString *mechanism = [self mechansimFromClassMethod:selector onClass:class];
  315. [[FLEXNetworkRecorder defaultRecorder] recordMechanism:mechanism forRequestID:requestID];
  316. NSURLConnectionAsyncCompletion completionWrapper = ^(NSURLResponse *response, NSData *data, NSError *connectionError) {
  317. [[FLEXNetworkRecorder defaultRecorder] recordResponseReceivedWithRequestID:requestID response:response];
  318. [[FLEXNetworkRecorder defaultRecorder] recordDataReceivedWithRequestID:requestID dataLength:[data length]];
  319. if (connectionError) {
  320. [[FLEXNetworkRecorder defaultRecorder] recordLoadingFailedWithRequestID:requestID error:connectionError];
  321. } else {
  322. [[FLEXNetworkRecorder defaultRecorder] recordLoadingFinishedWithRequestID:requestID responseBody:data];
  323. }
  324. // Call through to the original completion handler
  325. if (completion) {
  326. completion(response, data, connectionError);
  327. }
  328. };
  329. ((void(*)(id, SEL, id, id, id))objc_msgSend)(slf, swizzledSelector, request, queue, completionWrapper);
  330. } else {
  331. ((void(*)(id, SEL, id, id, id))objc_msgSend)(slf, swizzledSelector, request, queue, completion);
  332. }
  333. };
  334. [self replaceImplementationOfKnownSelector:selector onClass:class withBlock:asyncSwizzleBlock swizzledSelector:swizzledSelector];
  335. });
  336. }
  337. + (void)injectIntoNSURLConnectionSynchronousClassMethod
  338. {
  339. static dispatch_once_t onceToken;
  340. dispatch_once(&onceToken, ^{
  341. Class class = objc_getMetaClass(class_getName([NSURLConnection class]));
  342. SEL selector = @selector(sendSynchronousRequest:returningResponse:error:);
  343. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  344. NSData *(^syncSwizzleBlock)(Class, NSURLRequest *, NSURLResponse **, NSError **) = ^NSData *(Class slf, NSURLRequest *request, NSURLResponse **response, NSError **error) {
  345. NSData *data = nil;
  346. if ([FLEXNetworkObserver isEnabled]) {
  347. NSString *requestID = [self nextRequestID];
  348. [[FLEXNetworkRecorder defaultRecorder] recordRequestWillBeSentWithRequestID:requestID request:request redirectResponse:nil];
  349. NSString *mechanism = [self mechansimFromClassMethod:selector onClass:class];
  350. [[FLEXNetworkRecorder defaultRecorder] recordMechanism:mechanism forRequestID:requestID];
  351. NSError *temporaryError = nil;
  352. NSURLResponse *temporaryResponse = nil;
  353. data = ((id(*)(id, SEL, id, NSURLResponse **, NSError **))objc_msgSend)(slf, swizzledSelector, request, &temporaryResponse, &temporaryError);
  354. [[FLEXNetworkRecorder defaultRecorder] recordResponseReceivedWithRequestID:requestID response:temporaryResponse];
  355. [[FLEXNetworkRecorder defaultRecorder] recordDataReceivedWithRequestID:requestID dataLength:[data length]];
  356. if (temporaryError) {
  357. [[FLEXNetworkRecorder defaultRecorder] recordLoadingFailedWithRequestID:requestID error:temporaryError];
  358. } else {
  359. [[FLEXNetworkRecorder defaultRecorder] recordLoadingFinishedWithRequestID:requestID responseBody:data];
  360. }
  361. if (error) {
  362. *error = temporaryError;
  363. }
  364. if (response) {
  365. *response = temporaryResponse;
  366. }
  367. } else {
  368. data = ((id(*)(id, SEL, id, NSURLResponse **, NSError **))objc_msgSend)(slf, swizzledSelector, request, response, error);
  369. }
  370. return data;
  371. };
  372. [self replaceImplementationOfKnownSelector:selector onClass:class withBlock:syncSwizzleBlock swizzledSelector:swizzledSelector];
  373. });
  374. }
  375. + (void)injectIntoNSURLSessionAsyncDataAndDownloadTaskMethods
  376. {
  377. static dispatch_once_t onceToken;
  378. dispatch_once(&onceToken, ^{
  379. Class class = [NSURLSession class];
  380. // The method signatures here are close enough that we can use the same logic to inject into all of them.
  381. const SEL selectors[] = {
  382. @selector(dataTaskWithRequest:completionHandler:),
  383. @selector(dataTaskWithURL:completionHandler:),
  384. @selector(downloadTaskWithRequest:completionHandler:),
  385. @selector(downloadTaskWithResumeData:completionHandler:),
  386. @selector(downloadTaskWithURL:completionHandler:)
  387. };
  388. const int numSelectors = sizeof(selectors) / sizeof(SEL);
  389. for (int selectorIndex = 0; selectorIndex < numSelectors; selectorIndex++) {
  390. SEL selector = selectors[selectorIndex];
  391. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  392. if ([self instanceRespondsButDoesNotImplementSelector:selector class:class]) {
  393. // iOS 7 does not implement these methods on NSURLSession. We actually want to
  394. // swizzle __NSCFURLSession, which we can get from the class of the shared session
  395. class = [[NSURLSession sharedSession] class];
  396. }
  397. NSURLSessionTask *(^asyncDataOrDownloadSwizzleBlock)(Class, id, NSURLSessionAsyncCompletion) = ^NSURLSessionTask *(Class slf, id argument, NSURLSessionAsyncCompletion completion) {
  398. NSURLSessionTask *task = nil;
  399. // If completion block was not provided sender expect to receive delegated methods or does not
  400. // interested in callback at all. In this case we should just call original method implementation
  401. // with nil completion block.
  402. if ([FLEXNetworkObserver isEnabled] && completion) {
  403. NSString *requestID = [self nextRequestID];
  404. NSString *mechanism = [self mechansimFromClassMethod:selector onClass:class];
  405. NSURLSessionAsyncCompletion completionWrapper = [self asyncCompletionWrapperForRequestID:requestID mechanism:mechanism completion:completion];
  406. task = ((id(*)(id, SEL, id, id))objc_msgSend)(slf, swizzledSelector, argument, completionWrapper);
  407. [self setRequestID:requestID forConnectionOrTask:task];
  408. } else {
  409. task = ((id(*)(id, SEL, id, id))objc_msgSend)(slf, swizzledSelector, argument, completion);
  410. }
  411. return task;
  412. };
  413. [self replaceImplementationOfKnownSelector:selector onClass:class withBlock:asyncDataOrDownloadSwizzleBlock swizzledSelector:swizzledSelector];
  414. }
  415. });
  416. }
  417. + (void)injectIntoNSURLSessionAsyncUploadTaskMethods
  418. {
  419. static dispatch_once_t onceToken;
  420. dispatch_once(&onceToken, ^{
  421. Class class = [NSURLSession class];
  422. // The method signatures here are close enough that we can use the same logic to inject into both of them.
  423. // Note that they have 3 arguments, so we can't easily combine with the data and download method above.
  424. const SEL selectors[] = {
  425. @selector(uploadTaskWithRequest:fromData:completionHandler:),
  426. @selector(uploadTaskWithRequest:fromFile:completionHandler:)
  427. };
  428. const int numSelectors = sizeof(selectors) / sizeof(SEL);
  429. for (int selectorIndex = 0; selectorIndex < numSelectors; selectorIndex++) {
  430. SEL selector = selectors[selectorIndex];
  431. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  432. if ([self instanceRespondsButDoesNotImplementSelector:selector class:class]) {
  433. // iOS 7 does not implement these methods on NSURLSession. We actually want to
  434. // swizzle __NSCFURLSession, which we can get from the class of the shared session
  435. class = [[NSURLSession sharedSession] class];
  436. }
  437. NSURLSessionUploadTask *(^asyncUploadTaskSwizzleBlock)(Class, NSURLRequest *, id, NSURLSessionAsyncCompletion) = ^NSURLSessionUploadTask *(Class slf, NSURLRequest *request, id argument, NSURLSessionAsyncCompletion completion) {
  438. NSURLSessionUploadTask *task = nil;
  439. if ([FLEXNetworkObserver isEnabled]) {
  440. NSString *requestID = [self nextRequestID];
  441. NSString *mechanism = [self mechansimFromClassMethod:selector onClass:class];
  442. NSURLSessionAsyncCompletion completionWrapper = [self asyncCompletionWrapperForRequestID:requestID mechanism:mechanism completion:completion];
  443. task = ((id(*)(id, SEL, id, id, id))objc_msgSend)(slf, swizzledSelector, request, argument, completionWrapper);
  444. [self setRequestID:requestID forConnectionOrTask:task];
  445. } else {
  446. task = ((id(*)(id, SEL, id, id, id))objc_msgSend)(slf, swizzledSelector, request, argument, completion);
  447. }
  448. return task;
  449. };
  450. [self replaceImplementationOfKnownSelector:selector onClass:class withBlock:asyncUploadTaskSwizzleBlock swizzledSelector:swizzledSelector];
  451. }
  452. });
  453. }
  454. + (NSString *)mechansimFromClassMethod:(SEL)selector onClass:(Class)class
  455. {
  456. return [NSString stringWithFormat:@"+[%@ %@]", NSStringFromClass(class), NSStringFromSelector(selector)];
  457. }
  458. + (NSURLSessionAsyncCompletion)asyncCompletionWrapperForRequestID:(NSString *)requestID mechanism:(NSString *)mechanism completion:(NSURLSessionAsyncCompletion)completion
  459. {
  460. NSURLSessionAsyncCompletion completionWrapper = ^(id fileURLOrData, NSURLResponse *response, NSError *error) {
  461. [[FLEXNetworkRecorder defaultRecorder] recordMechanism:mechanism forRequestID:requestID];
  462. [[FLEXNetworkRecorder defaultRecorder] recordResponseReceivedWithRequestID:requestID response:response];
  463. NSData *data = nil;
  464. if ([fileURLOrData isKindOfClass:[NSURL class]]) {
  465. data = [NSData dataWithContentsOfURL:fileURLOrData];
  466. } else if ([fileURLOrData isKindOfClass:[NSData class]]) {
  467. data = fileURLOrData;
  468. }
  469. [[FLEXNetworkRecorder defaultRecorder] recordDataReceivedWithRequestID:requestID dataLength:[data length]];
  470. if (error) {
  471. [[FLEXNetworkRecorder defaultRecorder] recordLoadingFailedWithRequestID:requestID error:error];
  472. } else {
  473. [[FLEXNetworkRecorder defaultRecorder] recordLoadingFinishedWithRequestID:requestID responseBody:data];
  474. }
  475. // Call through to the original completion handler
  476. if (completion) {
  477. completion(fileURLOrData, response, error);
  478. }
  479. };
  480. return completionWrapper;
  481. }
  482. + (void)injectWillSendRequestIntoDelegateClass:(Class)cls
  483. {
  484. SEL selector = @selector(connection:willSendRequest:redirectResponse:);
  485. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  486. Protocol *protocol = @protocol(NSURLConnectionDataDelegate);
  487. if (!protocol) {
  488. protocol = @protocol(NSURLConnectionDelegate);
  489. }
  490. struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES);
  491. typedef NSURLRequest *(^NSURLConnectionWillSendRequestBlock)(id <NSURLConnectionDelegate> slf, NSURLConnection *connection, NSURLRequest *request, NSURLResponse *response);
  492. NSURLConnectionWillSendRequestBlock undefinedBlock = ^NSURLRequest *(id <NSURLConnectionDelegate> slf, NSURLConnection *connection, NSURLRequest *request, NSURLResponse *response) {
  493. [[FLEXNetworkObserver sharedObserver] connection:connection willSendRequest:request redirectResponse:response delegate:slf];
  494. return request;
  495. };
  496. NSURLConnectionWillSendRequestBlock implementationBlock = ^NSURLRequest *(id <NSURLConnectionDelegate> slf, NSURLConnection *connection, NSURLRequest *request, NSURLResponse *response) {
  497. __block NSURLRequest *returnValue = nil;
  498. [self sniffWithoutDuplicationForObject:connection selector:selector sniffingBlock:^{
  499. undefinedBlock(slf, connection, request, response);
  500. } originalImplementationBlock:^{
  501. returnValue = ((id(*)(id, SEL, id, id, id))objc_msgSend)(slf, swizzledSelector, connection, request, response);
  502. }];
  503. return returnValue;
  504. };
  505. [self replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription implementationBlock:implementationBlock undefinedBlock:undefinedBlock];
  506. }
  507. + (void)injectDidReceiveResponseIntoDelegateClass:(Class)cls
  508. {
  509. SEL selector = @selector(connection:didReceiveResponse:);
  510. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  511. Protocol *protocol = @protocol(NSURLConnectionDataDelegate);
  512. if (!protocol) {
  513. protocol = @protocol(NSURLConnectionDelegate);
  514. }
  515. struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES);
  516. typedef void (^NSURLConnectionDidReceiveResponseBlock)(id <NSURLConnectionDelegate> slf, NSURLConnection *connection, NSURLResponse *response);
  517. NSURLConnectionDidReceiveResponseBlock undefinedBlock = ^(id <NSURLConnectionDelegate> slf, NSURLConnection *connection, NSURLResponse *response) {
  518. [[FLEXNetworkObserver sharedObserver] connection:connection didReceiveResponse:response delegate:slf];
  519. };
  520. NSURLConnectionDidReceiveResponseBlock implementationBlock = ^(id <NSURLConnectionDelegate> slf, NSURLConnection *connection, NSURLResponse *response) {
  521. [self sniffWithoutDuplicationForObject:connection selector:selector sniffingBlock:^{
  522. undefinedBlock(slf, connection, response);
  523. } originalImplementationBlock:^{
  524. ((void(*)(id, SEL, id, id))objc_msgSend)(slf, swizzledSelector, connection, response);
  525. }];
  526. };
  527. [self replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription implementationBlock:implementationBlock undefinedBlock:undefinedBlock];
  528. }
  529. + (void)injectDidReceiveDataIntoDelegateClass:(Class)cls
  530. {
  531. SEL selector = @selector(connection:didReceiveData:);
  532. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  533. Protocol *protocol = @protocol(NSURLConnectionDataDelegate);
  534. if (!protocol) {
  535. protocol = @protocol(NSURLConnectionDelegate);
  536. }
  537. struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES);
  538. typedef void (^NSURLConnectionDidReceiveDataBlock)(id <NSURLConnectionDelegate> slf, NSURLConnection *connection, NSData *data);
  539. NSURLConnectionDidReceiveDataBlock undefinedBlock = ^(id <NSURLConnectionDelegate> slf, NSURLConnection *connection, NSData *data) {
  540. [[FLEXNetworkObserver sharedObserver] connection:connection didReceiveData:data delegate:slf];
  541. };
  542. NSURLConnectionDidReceiveDataBlock implementationBlock = ^(id <NSURLConnectionDelegate> slf, NSURLConnection *connection, NSData *data) {
  543. [self sniffWithoutDuplicationForObject:connection selector:selector sniffingBlock:^{
  544. undefinedBlock(slf, connection, data);
  545. } originalImplementationBlock:^{
  546. ((void(*)(id, SEL, id, id))objc_msgSend)(slf, swizzledSelector, connection, data);
  547. }];
  548. };
  549. [self replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription implementationBlock:implementationBlock undefinedBlock:undefinedBlock];
  550. }
  551. + (void)injectDidFinishLoadingIntoDelegateClass:(Class)cls
  552. {
  553. SEL selector = @selector(connectionDidFinishLoading:);
  554. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  555. Protocol *protocol = @protocol(NSURLConnectionDataDelegate);
  556. if (!protocol) {
  557. protocol = @protocol(NSURLConnectionDelegate);
  558. }
  559. struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES);
  560. typedef void (^NSURLConnectionDidFinishLoadingBlock)(id <NSURLConnectionDelegate> slf, NSURLConnection *connection);
  561. NSURLConnectionDidFinishLoadingBlock undefinedBlock = ^(id <NSURLConnectionDelegate> slf, NSURLConnection *connection) {
  562. [[FLEXNetworkObserver sharedObserver] connectionDidFinishLoading:connection delegate:slf];
  563. };
  564. NSURLConnectionDidFinishLoadingBlock implementationBlock = ^(id <NSURLConnectionDelegate> slf, NSURLConnection *connection) {
  565. [self sniffWithoutDuplicationForObject:connection selector:selector sniffingBlock:^{
  566. undefinedBlock(slf, connection);
  567. } originalImplementationBlock:^{
  568. ((void(*)(id, SEL, id))objc_msgSend)(slf, swizzledSelector, connection);
  569. }];
  570. };
  571. [self replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription implementationBlock:implementationBlock undefinedBlock:undefinedBlock];
  572. }
  573. + (void)injectDidFailWithErrorIntoDelegateClass:(Class)cls
  574. {
  575. SEL selector = @selector(connection:didFailWithError:);
  576. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  577. Protocol *protocol = @protocol(NSURLConnectionDelegate);
  578. struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES);
  579. typedef void (^NSURLConnectionDidFailWithErrorBlock)(id <NSURLConnectionDelegate> slf, NSURLConnection *connection, NSError *error);
  580. NSURLConnectionDidFailWithErrorBlock undefinedBlock = ^(id <NSURLConnectionDelegate> slf, NSURLConnection *connection, NSError *error) {
  581. [[FLEXNetworkObserver sharedObserver] connection:connection didFailWithError:error delegate:slf];
  582. };
  583. NSURLConnectionDidFailWithErrorBlock implementationBlock = ^(id <NSURLConnectionDelegate> slf, NSURLConnection *connection, NSError *error) {
  584. [self sniffWithoutDuplicationForObject:connection selector:selector sniffingBlock:^{
  585. undefinedBlock(slf, connection, error);
  586. } originalImplementationBlock:^{
  587. ((void(*)(id, SEL, id, id))objc_msgSend)(slf, swizzledSelector, connection, error);
  588. }];
  589. };
  590. [self replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription implementationBlock:implementationBlock undefinedBlock:undefinedBlock];
  591. }
  592. + (void)injectTaskWillPerformHTTPRedirectionIntoDelegateClass:(Class)cls
  593. {
  594. SEL selector = @selector(URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:);
  595. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  596. Protocol *protocol = @protocol(NSURLSessionTaskDelegate);
  597. struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES);
  598. typedef void (^NSURLSessionWillPerformHTTPRedirectionBlock)(id <NSURLSessionTaskDelegate> slf, NSURLSession *session, NSURLSessionTask *task, NSHTTPURLResponse *response, NSURLRequest *newRequest, void(^completionHandler)(NSURLRequest *));
  599. NSURLSessionWillPerformHTTPRedirectionBlock undefinedBlock = ^(id <NSURLSessionTaskDelegate> slf, NSURLSession *session, NSURLSessionTask *task, NSHTTPURLResponse *response, NSURLRequest *newRequest, void(^completionHandler)(NSURLRequest *)) {
  600. [[FLEXNetworkObserver sharedObserver] URLSession:session task:task willPerformHTTPRedirection:response newRequest:newRequest completionHandler:completionHandler delegate:slf];
  601. };
  602. NSURLSessionWillPerformHTTPRedirectionBlock implementationBlock = ^(id <NSURLSessionTaskDelegate> slf, NSURLSession *session, NSURLSessionTask *task, NSHTTPURLResponse *response, NSURLRequest *newRequest, void(^completionHandler)(NSURLRequest *)) {
  603. [self sniffWithoutDuplicationForObject:session selector:selector sniffingBlock:^{
  604. undefinedBlock(slf, session, task, response, newRequest, completionHandler);
  605. } originalImplementationBlock:^{
  606. ((id(*)(id, SEL, id, id, id, id, void(^)()))objc_msgSend)(slf, swizzledSelector, session, task, response, newRequest, completionHandler);
  607. }];
  608. };
  609. [self replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription implementationBlock:implementationBlock undefinedBlock:undefinedBlock];
  610. }
  611. + (void)injectTaskDidReceiveDataIntoDelegateClass:(Class)cls
  612. {
  613. SEL selector = @selector(URLSession:dataTask:didReceiveData:);
  614. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  615. Protocol *protocol = @protocol(NSURLSessionDataDelegate);
  616. struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES);
  617. typedef void (^NSURLSessionDidReceiveDataBlock)(id <NSURLSessionDataDelegate> slf, NSURLSession *session, NSURLSessionDataTask *dataTask, NSData *data);
  618. NSURLSessionDidReceiveDataBlock undefinedBlock = ^(id <NSURLSessionDataDelegate> slf, NSURLSession *session, NSURLSessionDataTask *dataTask, NSData *data) {
  619. [[FLEXNetworkObserver sharedObserver] URLSession:session dataTask:dataTask didReceiveData:data delegate:slf];
  620. };
  621. NSURLSessionDidReceiveDataBlock implementationBlock = ^(id <NSURLSessionDataDelegate> slf, NSURLSession *session, NSURLSessionDataTask *dataTask, NSData *data) {
  622. [self sniffWithoutDuplicationForObject:session selector:selector sniffingBlock:^{
  623. undefinedBlock(slf, session, dataTask, data);
  624. } originalImplementationBlock:^{
  625. ((void(*)(id, SEL, id, id, id))objc_msgSend)(slf, swizzledSelector, session, dataTask, data);
  626. }];
  627. };
  628. [self replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription implementationBlock:implementationBlock undefinedBlock:undefinedBlock];
  629. }
  630. + (void)injectDataTaskDidBecomeDownloadTaskIntoDelegateClass:(Class)cls
  631. {
  632. SEL selector = @selector(URLSession:dataTask:didBecomeDownloadTask:);
  633. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  634. Protocol *protocol = @protocol(NSURLSessionDataDelegate);
  635. struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES);
  636. typedef void (^NSURLSessionDidBecomeDownloadTaskBlock)(id <NSURLSessionDataDelegate> slf, NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLSessionDownloadTask *downloadTask);
  637. NSURLSessionDidBecomeDownloadTaskBlock undefinedBlock = ^(id <NSURLSessionDataDelegate> slf, NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLSessionDownloadTask *downloadTask) {
  638. [[FLEXNetworkObserver sharedObserver] URLSession:session dataTask:dataTask didBecomeDownloadTask:downloadTask delegate:slf];
  639. };
  640. NSURLSessionDidBecomeDownloadTaskBlock implementationBlock = ^(id <NSURLSessionDataDelegate> slf, NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLSessionDownloadTask *downloadTask) {
  641. [self sniffWithoutDuplicationForObject:session selector:selector sniffingBlock:^{
  642. undefinedBlock(slf, session, dataTask, downloadTask);
  643. } originalImplementationBlock:^{
  644. ((void(*)(id, SEL, id, id, id))objc_msgSend)(slf, swizzledSelector, session, dataTask, downloadTask);
  645. }];
  646. };
  647. [self replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription implementationBlock:implementationBlock undefinedBlock:undefinedBlock];
  648. }
  649. + (void)injectTaskDidReceiveResponseIntoDelegateClass:(Class)cls
  650. {
  651. SEL selector = @selector(URLSession:dataTask:didReceiveResponse:completionHandler:);
  652. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  653. Protocol *protocol = @protocol(NSURLSessionDataDelegate);
  654. struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES);
  655. typedef void (^NSURLSessionDidReceiveResponseBlock)(id <NSURLSessionDelegate> slf, NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLResponse *response, void(^completionHandler)(NSURLSessionResponseDisposition disposition));
  656. NSURLSessionDidReceiveResponseBlock undefinedBlock = ^(id <NSURLSessionDelegate> slf, NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLResponse *response, void(^completionHandler)(NSURLSessionResponseDisposition disposition)) {
  657. [[FLEXNetworkObserver sharedObserver] URLSession:session dataTask:dataTask didReceiveResponse:response completionHandler:completionHandler delegate:slf];
  658. };
  659. NSURLSessionDidReceiveResponseBlock implementationBlock = ^(id <NSURLSessionDelegate> slf, NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLResponse *response, void(^completionHandler)(NSURLSessionResponseDisposition disposition)) {
  660. [self sniffWithoutDuplicationForObject:session selector:selector sniffingBlock:^{
  661. undefinedBlock(slf, session, dataTask, response, completionHandler);
  662. } originalImplementationBlock:^{
  663. ((void(*)(id, SEL, id, id, id, void(^)()))objc_msgSend)(slf, swizzledSelector, session, dataTask, response, completionHandler);
  664. }];
  665. };
  666. [self replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription implementationBlock:implementationBlock undefinedBlock:undefinedBlock];
  667. }
  668. + (void)injectTaskDidCompleteWithErrorIntoDelegateClass:(Class)cls
  669. {
  670. SEL selector = @selector(URLSession:task:didCompleteWithError:);
  671. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  672. Protocol *protocol = @protocol(NSURLSessionTaskDelegate);
  673. struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES);
  674. typedef void (^NSURLSessionTaskDidCompleteWithErrorBlock)(id <NSURLSessionTaskDelegate> slf, NSURLSession *session, NSURLSessionTask *task, NSError *error);
  675. NSURLSessionTaskDidCompleteWithErrorBlock undefinedBlock = ^(id <NSURLSessionTaskDelegate> slf, NSURLSession *session, NSURLSessionTask *task, NSError *error) {
  676. [[FLEXNetworkObserver sharedObserver] URLSession:session task:task didCompleteWithError:error delegate:slf];
  677. };
  678. NSURLSessionTaskDidCompleteWithErrorBlock implementationBlock = ^(id <NSURLSessionTaskDelegate> slf, NSURLSession *session, NSURLSessionTask *task, NSError *error) {
  679. [self sniffWithoutDuplicationForObject:session selector:selector sniffingBlock:^{
  680. undefinedBlock(slf, session, task, error);
  681. } originalImplementationBlock:^{
  682. ((void(*)(id, SEL, id, id, id))objc_msgSend)(slf, swizzledSelector, session, task, error);
  683. }];
  684. };
  685. [self replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription implementationBlock:implementationBlock undefinedBlock:undefinedBlock];
  686. }
  687. // Used for overriding AFNetworking behavior
  688. + (void)injectRespondsToSelectorIntoDelegateClass:(Class)cls
  689. {
  690. SEL selector = @selector(respondsToSelector:);
  691. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  692. //Protocol *protocol = @protocol(NSURLSessionTaskDelegate);
  693. Method method = class_getInstanceMethod(cls, selector);
  694. struct objc_method_description methodDescription = *method_getDescription(method);
  695. BOOL (^undefinedBlock)(id <NSURLSessionTaskDelegate>, SEL) = ^(id slf, SEL sel) {
  696. return YES;
  697. };
  698. BOOL (^implementationBlock)(id <NSURLSessionTaskDelegate>, SEL) = ^(id <NSURLSessionTaskDelegate> slf, SEL sel) {
  699. if (sel == @selector(URLSession:dataTask:didReceiveResponse:completionHandler:)) {
  700. return undefinedBlock(slf, sel);
  701. }
  702. return ((BOOL(*)(id, SEL, SEL))objc_msgSend)(slf, swizzledSelector, sel);
  703. };
  704. [self replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription implementationBlock:implementationBlock undefinedBlock:undefinedBlock];
  705. }
  706. + (void)injectDownloadTaskDidFinishDownloadingIntoDelegateClass:(Class)cls
  707. {
  708. SEL selector = @selector(URLSession:downloadTask:didFinishDownloadingToURL:);
  709. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  710. Protocol *protocol = @protocol(NSURLSessionDownloadDelegate);
  711. struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES);
  712. typedef void (^NSURLSessionDownloadTaskDidFinishDownloadingBlock)(id <NSURLSessionTaskDelegate> slf, NSURLSession *session, NSURLSessionDownloadTask *task, NSURL *location);
  713. NSURLSessionDownloadTaskDidFinishDownloadingBlock undefinedBlock = ^(id <NSURLSessionTaskDelegate> slf, NSURLSession *session, NSURLSessionDownloadTask *task, NSURL *location) {
  714. NSData *data = [NSData dataWithContentsOfFile:location.relativePath];
  715. [[FLEXNetworkObserver sharedObserver] URLSession:session task:task didFinishDownloadingToURL:location data:data delegate:slf];
  716. };
  717. NSURLSessionDownloadTaskDidFinishDownloadingBlock implementationBlock = ^(id <NSURLSessionTaskDelegate> slf, NSURLSession *session, NSURLSessionDownloadTask *task, NSURL *location) {
  718. [self sniffWithoutDuplicationForObject:session selector:selector sniffingBlock:^{
  719. undefinedBlock(slf, session, task, location);
  720. } originalImplementationBlock:^{
  721. ((void(*)(id, SEL, id, id, id))objc_msgSend)(slf, swizzledSelector, session, task, location);
  722. }];
  723. };
  724. [self replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription implementationBlock:implementationBlock undefinedBlock:undefinedBlock];
  725. }
  726. + (void)injectDownloadTaskDidWriteDataIntoDelegateClass:(Class)cls
  727. {
  728. SEL selector = @selector(URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:);
  729. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  730. Protocol *protocol = @protocol(NSURLSessionDownloadDelegate);
  731. struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES);
  732. typedef void (^NSURLSessionDownloadTaskDidWriteDataBlock)(id <NSURLSessionTaskDelegate> slf, NSURLSession *session, NSURLSessionDownloadTask *task, int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite);
  733. NSURLSessionDownloadTaskDidWriteDataBlock undefinedBlock = ^(id <NSURLSessionTaskDelegate> slf, NSURLSession *session, NSURLSessionDownloadTask *task, int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite) {
  734. [[FLEXNetworkObserver sharedObserver] URLSession:session downloadTask:task didWriteData:bytesWritten totalBytesWritten:totalBytesWritten totalBytesExpectedToWrite:totalBytesExpectedToWrite delegate:slf];
  735. };
  736. NSURLSessionDownloadTaskDidWriteDataBlock implementationBlock = ^(id <NSURLSessionTaskDelegate> slf, NSURLSession *session, NSURLSessionDownloadTask *task, int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite) {
  737. [self sniffWithoutDuplicationForObject:session selector:selector sniffingBlock:^{
  738. undefinedBlock(slf, session, task, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite);
  739. } originalImplementationBlock:^{
  740. ((void(*)(id, SEL, id, id, int64_t, int64_t, int64_t))objc_msgSend)(slf, swizzledSelector, session, task, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite);
  741. }];
  742. };
  743. [self replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription implementationBlock:implementationBlock undefinedBlock:undefinedBlock];
  744. }
  745. static char const * const kFLEXRequestIDKey = "kFLEXRequestIDKey";
  746. + (NSString *)requestIDForConnectionOrTask:(id)connectionOrTask
  747. {
  748. NSString *requestID = objc_getAssociatedObject(connectionOrTask, kFLEXRequestIDKey);
  749. if (!requestID) {
  750. requestID = [self nextRequestID];
  751. [self setRequestID:requestID forConnectionOrTask:connectionOrTask];
  752. }
  753. return requestID;
  754. }
  755. + (void)setRequestID:(NSString *)requestID forConnectionOrTask:(id)connectionOrTask
  756. {
  757. objc_setAssociatedObject(connectionOrTask, kFLEXRequestIDKey, requestID, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
  758. }
  759. #pragma mark - Initialization
  760. - (id)init
  761. {
  762. self = [super init];
  763. if (self) {
  764. self.requestStatesForRequestIDs = [[NSMutableDictionary alloc] init];
  765. self.queue = dispatch_queue_create("com.flex.FLEXNetworkObserver", DISPATCH_QUEUE_SERIAL);
  766. }
  767. return self;
  768. }
  769. #pragma mark - Private Methods
  770. - (void)performBlock:(dispatch_block_t)block
  771. {
  772. if (self.isEnabled) {
  773. dispatch_async(_queue, block);
  774. }
  775. }
  776. - (FLEXInternalRequestState *)requestStateForRequestID:(NSString *)requestID
  777. {
  778. FLEXInternalRequestState *requestState = [self.requestStatesForRequestIDs objectForKey:requestID];
  779. if (!requestState) {
  780. requestState = [[FLEXInternalRequestState alloc] init];
  781. [self.requestStatesForRequestIDs setObject:requestState forKey:requestID];
  782. }
  783. return requestState;
  784. }
  785. - (void)removeRequestStateForRequestID:(NSString *)requestID
  786. {
  787. [self.requestStatesForRequestIDs removeObjectForKey:requestID];
  788. }
  789. @end
  790. @implementation FLEXNetworkObserver (NSURLConnectionHelpers)
  791. - (void)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response delegate:(id<NSURLConnectionDelegate>)delegate
  792. {
  793. [self performBlock:^{
  794. NSString *requestID = [[self class] requestIDForConnectionOrTask:connection];
  795. FLEXInternalRequestState *requestState = [self requestStateForRequestID:requestID];
  796. requestState.request = request;
  797. [[FLEXNetworkRecorder defaultRecorder] recordRequestWillBeSentWithRequestID:requestID request:request redirectResponse:response];
  798. NSString *mechanism = [NSString stringWithFormat:@"NSURLConnection (delegate: %@)", [delegate class]];
  799. [[FLEXNetworkRecorder defaultRecorder] recordMechanism:mechanism forRequestID:requestID];
  800. }];
  801. }
  802. - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response delegate:(id<NSURLConnectionDelegate>)delegate
  803. {
  804. [self performBlock:^{
  805. NSString *requestID = [[self class] requestIDForConnectionOrTask:connection];
  806. FLEXInternalRequestState *requestState = [self requestStateForRequestID:requestID];
  807. NSMutableData *dataAccumulator = nil;
  808. if (response.expectedContentLength < 0) {
  809. dataAccumulator = [[NSMutableData alloc] init];
  810. } else {
  811. dataAccumulator = [[NSMutableData alloc] initWithCapacity:(NSUInteger)response.expectedContentLength];
  812. }
  813. requestState.dataAccumulator = dataAccumulator;
  814. [[FLEXNetworkRecorder defaultRecorder] recordResponseReceivedWithRequestID:requestID response:response];
  815. }];
  816. }
  817. - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data delegate:(id<NSURLConnectionDelegate>)delegate
  818. {
  819. // Just to be safe since we're doing this async
  820. data = [data copy];
  821. [self performBlock:^{
  822. NSString *requestID = [[self class] requestIDForConnectionOrTask:connection];
  823. FLEXInternalRequestState *requestState = [self requestStateForRequestID:requestID];
  824. [requestState.dataAccumulator appendData:data];
  825. [[FLEXNetworkRecorder defaultRecorder] recordDataReceivedWithRequestID:requestID dataLength:data.length];
  826. }];
  827. }
  828. - (void)connectionDidFinishLoading:(NSURLConnection *)connection delegate:(id<NSURLConnectionDelegate>)delegate
  829. {
  830. [self performBlock:^{
  831. NSString *requestID = [[self class] requestIDForConnectionOrTask:connection];
  832. FLEXInternalRequestState *requestState = [self requestStateForRequestID:requestID];
  833. [[FLEXNetworkRecorder defaultRecorder] recordLoadingFinishedWithRequestID:requestID responseBody:requestState.dataAccumulator];
  834. [self removeRequestStateForRequestID:requestID];
  835. }];
  836. }
  837. - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error delegate:(id<NSURLConnectionDelegate>)delegate
  838. {
  839. [self performBlock:^{
  840. NSString *requestID = [[self class] requestIDForConnectionOrTask:connection];
  841. FLEXInternalRequestState *requestState = [self requestStateForRequestID:requestID];
  842. // Cancellations can occur prior to the willSendRequest:... NSURLConnection delegate call.
  843. // These are pretty common and clutter up the logs. Only record the failure if the recorder already knows about the request through willSendRequest:...
  844. if (requestState.request) {
  845. [[FLEXNetworkRecorder defaultRecorder] recordLoadingFailedWithRequestID:requestID error:error];
  846. }
  847. [self removeRequestStateForRequestID:requestID];
  848. }];
  849. }
  850. - (void)connectionWillCancel:(NSURLConnection *)connection
  851. {
  852. [self performBlock:^{
  853. // Mimic the behavior of NSURLSession which is to create an error on cancellation.
  854. NSDictionary *userInfo = @{ NSLocalizedDescriptionKey : @"cancelled" };
  855. NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorCancelled userInfo:userInfo];
  856. [self connection:connection didFailWithError:error delegate:nil];
  857. }];
  858. }
  859. @end
  860. @implementation FLEXNetworkObserver (NSURLSessionTaskHelpers)
  861. - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task willPerformHTTPRedirection:(NSHTTPURLResponse *)response newRequest:(NSURLRequest *)request completionHandler:(void (^)(NSURLRequest *))completionHandler delegate:(id<NSURLSessionDelegate>)delegate
  862. {
  863. [self performBlock:^{
  864. NSString *requestID = [[self class] requestIDForConnectionOrTask:task];
  865. [[FLEXNetworkRecorder defaultRecorder] recordRequestWillBeSentWithRequestID:requestID request:request redirectResponse:response];
  866. }];
  867. }
  868. - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler delegate:(id<NSURLSessionDelegate>)delegate
  869. {
  870. [self performBlock:^{
  871. NSString *requestID = [[self class] requestIDForConnectionOrTask:dataTask];
  872. FLEXInternalRequestState *requestState = [self requestStateForRequestID:requestID];
  873. NSMutableData *dataAccumulator = nil;
  874. if (response.expectedContentLength < 0) {
  875. dataAccumulator = [[NSMutableData alloc] init];
  876. } else {
  877. dataAccumulator = [[NSMutableData alloc] initWithCapacity:(NSUInteger)response.expectedContentLength];
  878. }
  879. requestState.dataAccumulator = dataAccumulator;
  880. NSString *requestMechanism = [NSString stringWithFormat:@"NSURLSessionDataTask (delegate: %@)", [delegate class]];
  881. [[FLEXNetworkRecorder defaultRecorder] recordMechanism:requestMechanism forRequestID:requestID];
  882. [[FLEXNetworkRecorder defaultRecorder] recordResponseReceivedWithRequestID:requestID response:response];
  883. }];
  884. }
  885. - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didBecomeDownloadTask:(NSURLSessionDownloadTask *)downloadTask delegate:(id<NSURLSessionDelegate>)delegate
  886. {
  887. [self performBlock:^{
  888. // By setting the request ID of the download task to match the data task,
  889. // it can pick up where the data task left off.
  890. NSString *requestID = [[self class] requestIDForConnectionOrTask:dataTask];
  891. [[self class] setRequestID:requestID forConnectionOrTask:downloadTask];
  892. }];
  893. }
  894. - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data delegate:(id<NSURLSessionDelegate>)delegate
  895. {
  896. // Just to be safe since we're doing this async
  897. data = [data copy];
  898. [self performBlock:^{
  899. NSString *requestID = [[self class] requestIDForConnectionOrTask:dataTask];
  900. FLEXInternalRequestState *requestState = [self requestStateForRequestID:requestID];
  901. [requestState.dataAccumulator appendData:data];
  902. [[FLEXNetworkRecorder defaultRecorder] recordDataReceivedWithRequestID:requestID dataLength:data.length];
  903. }];
  904. }
  905. - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error delegate:(id<NSURLSessionDelegate>)delegate
  906. {
  907. [self performBlock:^{
  908. NSString *requestID = [[self class] requestIDForConnectionOrTask:task];
  909. FLEXInternalRequestState *requestState = [self requestStateForRequestID:requestID];
  910. if (error) {
  911. [[FLEXNetworkRecorder defaultRecorder] recordLoadingFailedWithRequestID:requestID error:error];
  912. } else {
  913. [[FLEXNetworkRecorder defaultRecorder] recordLoadingFinishedWithRequestID:requestID responseBody:requestState.dataAccumulator];
  914. }
  915. [self removeRequestStateForRequestID:requestID];
  916. }];
  917. }
  918. - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite delegate:(id<NSURLSessionDelegate>)delegate
  919. {
  920. [self performBlock:^{
  921. NSString *requestID = [[self class] requestIDForConnectionOrTask:downloadTask];
  922. FLEXInternalRequestState *requestState = [self requestStateForRequestID:requestID];
  923. if (!requestState.dataAccumulator) {
  924. NSUInteger unsignedBytesExpectedToWrite = totalBytesExpectedToWrite > 0 ? totalBytesExpectedToWrite : 0;
  925. requestState.dataAccumulator = [[NSMutableData alloc] initWithCapacity:unsignedBytesExpectedToWrite];
  926. [[FLEXNetworkRecorder defaultRecorder] recordResponseReceivedWithRequestID:requestID response:downloadTask.response];
  927. NSString *requestMechanism = [NSString stringWithFormat:@"NSURLSessionDownloadTask (delegate: %@)", [delegate class]];
  928. [[FLEXNetworkRecorder defaultRecorder] recordMechanism:requestMechanism forRequestID:requestID];
  929. }
  930. [[FLEXNetworkRecorder defaultRecorder] recordDataReceivedWithRequestID:requestID dataLength:bytesWritten];
  931. }];
  932. }
  933. - (void)URLSession:(NSURLSession *)session task:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location data:(NSData *)data delegate:(id<NSURLSessionDelegate>)delegate
  934. {
  935. data = [data copy];
  936. [self performBlock:^{
  937. NSString *requestID = [[self class] requestIDForConnectionOrTask:downloadTask];
  938. FLEXInternalRequestState *requestState = [self requestStateForRequestID:requestID];
  939. [requestState.dataAccumulator appendData:data];
  940. }];
  941. }
  942. - (void)URLSessionTaskWillResume:(NSURLSessionTask *)task
  943. {
  944. // Since resume can be called multiple times on the same task, only treat the first resume as
  945. // the equivalent to connection:willSendRequest:...
  946. [self performBlock:^{
  947. NSString *requestID = [[self class] requestIDForConnectionOrTask:task];
  948. FLEXInternalRequestState *requestState = [self requestStateForRequestID:requestID];
  949. if (!requestState.request) {
  950. requestState.request = task.currentRequest;
  951. [[FLEXNetworkRecorder defaultRecorder] recordRequestWillBeSentWithRequestID:requestID request:task.currentRequest redirectResponse:nil];
  952. }
  953. }];
  954. }
  955. @end