FLEXNetworkObserver.m 57 KB

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