FLEXNetworkObserver.m 56 KB

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