FLEXNetworkObserver.m 59 KB

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