FLEXNetworkObserver.m 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050
  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. @interface FLEXInternalRequestState : NSObject
  22. @property (nonatomic, copy) NSURLRequest *request;
  23. @property (nonatomic, strong) NSMutableData *dataAccumulator;
  24. @property (nonatomic, copy) NSString *requestID;
  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 *connectionStates;
  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)replaceImplementationOfSelector:(SEL)selector withSelector:(SEL)swizzledSelector forClass:(Class)cls withMethodDescription:(struct objc_method_description)methodDescription implementationBlock:(id)implementationBlock undefinedBlock:(id)undefinedBlock
  146. {
  147. if ([self instanceRespondsButDoesNotImplementSelector:selector class:cls]) {
  148. return;
  149. }
  150. IMP implementation = imp_implementationWithBlock((id)([cls instancesRespondToSelector:selector] ? implementationBlock : undefinedBlock));
  151. Method oldMethod = class_getInstanceMethod(cls, selector);
  152. if (oldMethod) {
  153. class_addMethod(cls, swizzledSelector, implementation, methodDescription.types);
  154. Method newMethod = class_getInstanceMethod(cls, swizzledSelector);
  155. method_exchangeImplementations(oldMethod, newMethod);
  156. } else {
  157. class_addMethod(cls, selector, implementation, methodDescription.types);
  158. }
  159. }
  160. #pragma mark - Delegate Injection
  161. + (void)injectIntoAllNSURLConnectionDelegateClasses
  162. {
  163. // Only allow swizzling once.
  164. static dispatch_once_t onceToken;
  165. dispatch_once(&onceToken, ^{
  166. // Swizzle any classes that implement one of these selectors.
  167. const SEL selectors[] = {
  168. @selector(connectionDidFinishLoading:),
  169. @selector(connection:willSendRequest:redirectResponse:),
  170. @selector(connection:didReceiveResponse:),
  171. @selector(connection:didReceiveData:),
  172. @selector(connection:didFailWithError:),
  173. @selector(URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:),
  174. @selector(URLSession:dataTask:didReceiveData:),
  175. @selector(URLSession:dataTask:didReceiveResponse:completionHandler:),
  176. @selector(URLSession:task:didCompleteWithError:),
  177. @selector(URLSession:dataTask:didBecomeDownloadTask:delegate:),
  178. @selector(URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:),
  179. @selector(URLSession:downloadTask:didFinishDownloadingToURL:)
  180. };
  181. const int numSelectors = sizeof(selectors) / sizeof(SEL);
  182. Class *classes = NULL;
  183. int numClasses = objc_getClassList(NULL, 0);
  184. if (numClasses > 0) {
  185. classes = (__unsafe_unretained Class *)malloc(sizeof(Class) * numClasses);
  186. numClasses = objc_getClassList(classes, numClasses);
  187. for (NSInteger classIndex = 0; classIndex < numClasses; ++classIndex) {
  188. Class class = classes[classIndex];
  189. if (class == [FLEXNetworkObserver class]) {
  190. continue;
  191. }
  192. // Use the runtime API rather than the methods on NSObject to avoid sending messages to
  193. // classes we're not interested in swizzling. Otherwise we hit +initialize on all classes.
  194. // NOTE: calling class_getInstanceMethod() DOES send +initialize to the class. That's why we iterate through the method list.
  195. unsigned int methodCount = 0;
  196. Method *methods = class_copyMethodList(class, &methodCount);
  197. BOOL matchingSelectorFound = NO;
  198. for (unsigned int methodIndex = 0; methodIndex < methodCount; methodIndex++) {
  199. for (int selectorIndex = 0; selectorIndex < numSelectors; ++selectorIndex) {
  200. if (method_getName(methods[methodIndex]) == selectors[selectorIndex]) {
  201. [self injectIntoDelegateClass:class];
  202. matchingSelectorFound = YES;
  203. break;
  204. }
  205. }
  206. if (matchingSelectorFound) {
  207. break;
  208. }
  209. }
  210. free(methods);
  211. }
  212. free(classes);
  213. }
  214. [self injectIntoNSURLConnectionCancel];
  215. [self injectIntoNSURLSessionTaskResume];
  216. });
  217. }
  218. + (void)injectIntoDelegateClass:(Class)cls
  219. {
  220. // Connections
  221. [self injectWillSendRequestIntoDelegateClass:cls];
  222. [self injectDidReceiveDataIntoDelegateClass:cls];
  223. [self injectDidReceiveResponseIntoDelegateClass:cls];
  224. [self injectDidFinishLoadingIntoDelegateClass:cls];
  225. [self injectDidFailWithErrorIntoDelegateClass:cls];
  226. // Sessions
  227. [self injectTaskWillPerformHTTPRedirectionIntoDelegateClass:cls];
  228. [self injectTaskDidReceiveDataIntoDelegateClass:cls];
  229. [self injectTaskDidReceiveResponseIntoDelegateClass:cls];
  230. [self injectTaskDidCompleteWithErrorIntoDelegateClass:cls];
  231. [self injectRespondsToSelectorIntoDelegateClass:cls];
  232. // Data tasks
  233. [self injectDataTaskDidBecomeDownloadTaskIntoDelegateClass:cls];
  234. // Download tasks
  235. [self injectDownloadTaskDidWriteDataIntoDelegateClass:cls];
  236. [self injectDownloadTaskDidFinishDownloadingIntoDelegateClass:cls];
  237. }
  238. + (void)injectIntoNSURLConnectionCancel
  239. {
  240. Class class = [NSURLConnection class];
  241. SEL selector = @selector(cancel);
  242. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  243. Method originalCancel = class_getInstanceMethod(class, selector);
  244. void (^swizzleBlock)(NSURLConnection *) = ^(NSURLConnection *slf) {
  245. [[FLEXNetworkObserver sharedObserver] connectionWillCancel:slf];
  246. ((void(*)(id, SEL))objc_msgSend)(slf, swizzledSelector);
  247. };
  248. IMP implementation = imp_implementationWithBlock(swizzleBlock);
  249. class_addMethod(class, swizzledSelector, implementation, method_getTypeEncoding(originalCancel));
  250. Method newCancel = class_getInstanceMethod(class, swizzledSelector);
  251. method_exchangeImplementations(originalCancel, newCancel);
  252. }
  253. + (void)injectIntoNSURLSessionTaskResume
  254. {
  255. Class class = [NSURLSessionTask class];
  256. SEL selector = @selector(resume);
  257. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  258. Method originalResume = class_getInstanceMethod(class, selector);
  259. void (^swizzleBlock)(NSURLSessionTask *) = ^(NSURLSessionTask *slf) {
  260. [[FLEXNetworkObserver sharedObserver] URLSessionTaskWillResume:slf];
  261. ((void(*)(id, SEL))objc_msgSend)(slf, swizzledSelector);
  262. };
  263. IMP implementation = imp_implementationWithBlock(swizzleBlock);
  264. class_addMethod(class, swizzledSelector, implementation, method_getTypeEncoding(originalResume));
  265. Method newResume = class_getInstanceMethod(class, swizzledSelector);
  266. method_exchangeImplementations(originalResume, newResume);
  267. }
  268. + (void)injectWillSendRequestIntoDelegateClass:(Class)cls
  269. {
  270. SEL selector = @selector(connection:willSendRequest:redirectResponse:);
  271. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  272. Protocol *protocol = @protocol(NSURLConnectionDataDelegate);
  273. if (!protocol) {
  274. protocol = @protocol(NSURLConnectionDelegate);
  275. }
  276. struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES);
  277. typedef NSURLRequest *(^NSURLConnectionWillSendRequestBlock)(id <NSURLConnectionDelegate> slf, NSURLConnection *connection, NSURLRequest *request, NSURLResponse *response);
  278. NSURLConnectionWillSendRequestBlock undefinedBlock = ^NSURLRequest *(id <NSURLConnectionDelegate> slf, NSURLConnection *connection, NSURLRequest *request, NSURLResponse *response) {
  279. [[FLEXNetworkObserver sharedObserver] connection:connection willSendRequest:request redirectResponse:response delegate:slf];
  280. return request;
  281. };
  282. NSURLConnectionWillSendRequestBlock implementationBlock = ^NSURLRequest *(id <NSURLConnectionDelegate> slf, NSURLConnection *connection, NSURLRequest *request, NSURLResponse *response) {
  283. __block NSURLRequest *returnValue = nil;
  284. [self sniffWithoutDuplicationForObject:connection selector:selector sniffingBlock:^{
  285. undefinedBlock(slf, connection, request, response);
  286. } originalImplementationBlock:^{
  287. returnValue = ((id(*)(id, SEL, id, id, id))objc_msgSend)(slf, swizzledSelector, connection, request, response);
  288. }];
  289. return returnValue;
  290. };
  291. [self replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription implementationBlock:implementationBlock undefinedBlock:undefinedBlock];
  292. }
  293. + (void)injectDidReceiveResponseIntoDelegateClass:(Class)cls
  294. {
  295. SEL selector = @selector(connection:didReceiveResponse:);
  296. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  297. Protocol *protocol = @protocol(NSURLConnectionDataDelegate);
  298. if (!protocol) {
  299. protocol = @protocol(NSURLConnectionDelegate);
  300. }
  301. struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES);
  302. typedef void (^NSURLConnectionDidReceiveResponseBlock)(id <NSURLConnectionDelegate> slf, NSURLConnection *connection, NSURLResponse *response);
  303. NSURLConnectionDidReceiveResponseBlock undefinedBlock = ^(id <NSURLConnectionDelegate> slf, NSURLConnection *connection, NSURLResponse *response) {
  304. [[FLEXNetworkObserver sharedObserver] connection:connection didReceiveResponse:response delegate:slf];
  305. };
  306. NSURLConnectionDidReceiveResponseBlock implementationBlock = ^(id <NSURLConnectionDelegate> slf, NSURLConnection *connection, NSURLResponse *response) {
  307. [self sniffWithoutDuplicationForObject:connection selector:selector sniffingBlock:^{
  308. undefinedBlock(slf, connection, response);
  309. } originalImplementationBlock:^{
  310. ((void(*)(id, SEL, id, id))objc_msgSend)(slf, swizzledSelector, connection, response);
  311. }];
  312. };
  313. [self replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription implementationBlock:implementationBlock undefinedBlock:undefinedBlock];
  314. }
  315. + (void)injectDidReceiveDataIntoDelegateClass:(Class)cls
  316. {
  317. SEL selector = @selector(connection:didReceiveData:);
  318. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  319. Protocol *protocol = @protocol(NSURLConnectionDataDelegate);
  320. if (!protocol) {
  321. protocol = @protocol(NSURLConnectionDelegate);
  322. }
  323. struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES);
  324. typedef void (^NSURLConnectionDidReceiveDataBlock)(id <NSURLConnectionDelegate> slf, NSURLConnection *connection, NSData *data);
  325. NSURLConnectionDidReceiveDataBlock undefinedBlock = ^(id <NSURLConnectionDelegate> slf, NSURLConnection *connection, NSData *data) {
  326. [[FLEXNetworkObserver sharedObserver] connection:connection didReceiveData:data delegate:slf];
  327. };
  328. NSURLConnectionDidReceiveDataBlock implementationBlock = ^(id <NSURLConnectionDelegate> slf, NSURLConnection *connection, NSData *data) {
  329. [self sniffWithoutDuplicationForObject:connection selector:selector sniffingBlock:^{
  330. undefinedBlock(slf, connection, data);
  331. } originalImplementationBlock:^{
  332. ((void(*)(id, SEL, id, id))objc_msgSend)(slf, swizzledSelector, connection, data);
  333. }];
  334. };
  335. [self replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription implementationBlock:implementationBlock undefinedBlock:undefinedBlock];
  336. }
  337. + (void)injectDidFinishLoadingIntoDelegateClass:(Class)cls
  338. {
  339. SEL selector = @selector(connectionDidFinishLoading:);
  340. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  341. Protocol *protocol = @protocol(NSURLConnectionDataDelegate);
  342. if (!protocol) {
  343. protocol = @protocol(NSURLConnectionDelegate);
  344. }
  345. struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES);
  346. typedef void (^NSURLConnectionDidFinishLoadingBlock)(id <NSURLConnectionDelegate> slf, NSURLConnection *connection);
  347. NSURLConnectionDidFinishLoadingBlock undefinedBlock = ^(id <NSURLConnectionDelegate> slf, NSURLConnection *connection) {
  348. [[FLEXNetworkObserver sharedObserver] connectionDidFinishLoading:connection delegate:slf];
  349. };
  350. NSURLConnectionDidFinishLoadingBlock implementationBlock = ^(id <NSURLConnectionDelegate> slf, NSURLConnection *connection) {
  351. [self sniffWithoutDuplicationForObject:connection selector:selector sniffingBlock:^{
  352. undefinedBlock(slf, connection);
  353. } originalImplementationBlock:^{
  354. ((void(*)(id, SEL, id))objc_msgSend)(slf, swizzledSelector, connection);
  355. }];
  356. };
  357. [self replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription implementationBlock:implementationBlock undefinedBlock:undefinedBlock];
  358. }
  359. + (void)injectDidFailWithErrorIntoDelegateClass:(Class)cls
  360. {
  361. SEL selector = @selector(connection:didFailWithError:);
  362. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  363. Protocol *protocol = @protocol(NSURLConnectionDelegate);
  364. struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES);
  365. typedef void (^NSURLConnectionDidFailWithErrorBlock)(id <NSURLConnectionDelegate> slf, NSURLConnection *connection, NSError *error);
  366. NSURLConnectionDidFailWithErrorBlock undefinedBlock = ^(id <NSURLConnectionDelegate> slf, NSURLConnection *connection, NSError *error) {
  367. [[FLEXNetworkObserver sharedObserver] connection:connection didFailWithError:error delegate:slf];
  368. };
  369. NSURLConnectionDidFailWithErrorBlock implementationBlock = ^(id <NSURLConnectionDelegate> slf, NSURLConnection *connection, NSError *error) {
  370. [self sniffWithoutDuplicationForObject:connection selector:selector sniffingBlock:^{
  371. undefinedBlock(slf, connection, error);
  372. } originalImplementationBlock:^{
  373. ((void(*)(id, SEL, id, id))objc_msgSend)(slf, swizzledSelector, connection, error);
  374. }];
  375. };
  376. [self replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription implementationBlock:implementationBlock undefinedBlock:undefinedBlock];
  377. }
  378. + (void)injectTaskWillPerformHTTPRedirectionIntoDelegateClass:(Class)cls
  379. {
  380. SEL selector = @selector(URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:);
  381. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  382. Protocol *protocol = @protocol(NSURLSessionTaskDelegate);
  383. struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES);
  384. typedef void (^NSURLSessionWillPerformHTTPRedirectionBlock)(id <NSURLSessionTaskDelegate> slf, NSURLSession *session, NSURLSessionTask *task, NSHTTPURLResponse *response, NSURLRequest *newRequest, void(^completionHandler)(NSURLRequest *));
  385. NSURLSessionWillPerformHTTPRedirectionBlock undefinedBlock = ^(id <NSURLSessionTaskDelegate> slf, NSURLSession *session, NSURLSessionTask *task, NSHTTPURLResponse *response, NSURLRequest *newRequest, void(^completionHandler)(NSURLRequest *)) {
  386. [[FLEXNetworkObserver sharedObserver] URLSession:session task:task willPerformHTTPRedirection:response newRequest:newRequest completionHandler:completionHandler delegate:slf];
  387. };
  388. NSURLSessionWillPerformHTTPRedirectionBlock implementationBlock = ^(id <NSURLSessionTaskDelegate> slf, NSURLSession *session, NSURLSessionTask *task, NSHTTPURLResponse *response, NSURLRequest *newRequest, void(^completionHandler)(NSURLRequest *)) {
  389. [self sniffWithoutDuplicationForObject:session selector:selector sniffingBlock:^{
  390. undefinedBlock(slf, session, task, response, newRequest, completionHandler);
  391. } originalImplementationBlock:^{
  392. ((id(*)(id, SEL, id, id, id, id, void(^)()))objc_msgSend)(slf, swizzledSelector, session, task, response, newRequest, completionHandler);
  393. }];
  394. };
  395. [self replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription implementationBlock:implementationBlock undefinedBlock:undefinedBlock];
  396. }
  397. + (void)injectTaskDidReceiveDataIntoDelegateClass:(Class)cls
  398. {
  399. SEL selector = @selector(URLSession:dataTask:didReceiveData:);
  400. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  401. Protocol *protocol = @protocol(NSURLSessionDataDelegate);
  402. struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES);
  403. typedef void (^NSURLSessionDidReceiveDataBlock)(id <NSURLSessionDataDelegate> slf, NSURLSession *session, NSURLSessionDataTask *dataTask, NSData *data);
  404. NSURLSessionDidReceiveDataBlock undefinedBlock = ^(id <NSURLSessionDataDelegate> slf, NSURLSession *session, NSURLSessionDataTask *dataTask, NSData *data) {
  405. [[FLEXNetworkObserver sharedObserver] URLSession:session dataTask:dataTask didReceiveData:data delegate:slf];
  406. };
  407. NSURLSessionDidReceiveDataBlock implementationBlock = ^(id <NSURLSessionDataDelegate> slf, NSURLSession *session, NSURLSessionDataTask *dataTask, NSData *data) {
  408. [self sniffWithoutDuplicationForObject:session selector:selector sniffingBlock:^{
  409. undefinedBlock(slf, session, dataTask, data);
  410. } originalImplementationBlock:^{
  411. ((void(*)(id, SEL, id, id, id))objc_msgSend)(slf, swizzledSelector, session, dataTask, data);
  412. }];
  413. };
  414. [self replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription implementationBlock:implementationBlock undefinedBlock:undefinedBlock];
  415. }
  416. + (void)injectDataTaskDidBecomeDownloadTaskIntoDelegateClass:(Class)cls
  417. {
  418. SEL selector = @selector(URLSession:dataTask:didBecomeDownloadTask:);
  419. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  420. Protocol *protocol = @protocol(NSURLSessionDataDelegate);
  421. struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES);
  422. typedef void (^NSURLSessionDidBecomeDownloadTaskBlock)(id <NSURLSessionDataDelegate> slf, NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLSessionDownloadTask *downloadTask);
  423. NSURLSessionDidBecomeDownloadTaskBlock undefinedBlock = ^(id <NSURLSessionDataDelegate> slf, NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLSessionDownloadTask *downloadTask) {
  424. [[FLEXNetworkObserver sharedObserver] URLSession:session dataTask:dataTask didBecomeDownloadTask:downloadTask delegate:slf];
  425. };
  426. NSURLSessionDidBecomeDownloadTaskBlock implementationBlock = ^(id <NSURLSessionDataDelegate> slf, NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLSessionDownloadTask *downloadTask) {
  427. [self sniffWithoutDuplicationForObject:session selector:selector sniffingBlock:^{
  428. undefinedBlock(slf, session, dataTask, downloadTask);
  429. } originalImplementationBlock:^{
  430. ((void(*)(id, SEL, id, id, id))objc_msgSend)(slf, swizzledSelector, session, dataTask, downloadTask);
  431. }];
  432. };
  433. [self replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription implementationBlock:implementationBlock undefinedBlock:undefinedBlock];
  434. }
  435. + (void)injectTaskDidReceiveResponseIntoDelegateClass:(Class)cls
  436. {
  437. SEL selector = @selector(URLSession:dataTask:didReceiveResponse:completionHandler:);
  438. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  439. Protocol *protocol = @protocol(NSURLSessionDataDelegate);
  440. struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES);
  441. typedef void (^NSURLSessionDidReceiveResponseBlock)(id <NSURLSessionDelegate> slf, NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLResponse *response, void(^completionHandler)(NSURLSessionResponseDisposition disposition));
  442. NSURLSessionDidReceiveResponseBlock undefinedBlock = ^(id <NSURLSessionDelegate> slf, NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLResponse *response, void(^completionHandler)(NSURLSessionResponseDisposition disposition)) {
  443. [[FLEXNetworkObserver sharedObserver] URLSession:session dataTask:dataTask didReceiveResponse:response completionHandler:completionHandler delegate:slf];
  444. };
  445. NSURLSessionDidReceiveResponseBlock implementationBlock = ^(id <NSURLSessionDelegate> slf, NSURLSession *session, NSURLSessionDataTask *dataTask, NSURLResponse *response, void(^completionHandler)(NSURLSessionResponseDisposition disposition)) {
  446. [self sniffWithoutDuplicationForObject:session selector:selector sniffingBlock:^{
  447. undefinedBlock(slf, session, dataTask, response, completionHandler);
  448. } originalImplementationBlock:^{
  449. ((void(*)(id, SEL, id, id, id, void(^)()))objc_msgSend)(slf, swizzledSelector, session, dataTask, response, completionHandler);
  450. }];
  451. };
  452. [self replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription implementationBlock:implementationBlock undefinedBlock:undefinedBlock];
  453. }
  454. + (void)injectTaskDidCompleteWithErrorIntoDelegateClass:(Class)cls
  455. {
  456. SEL selector = @selector(URLSession:task:didCompleteWithError:);
  457. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  458. Protocol *protocol = @protocol(NSURLSessionTaskDelegate);
  459. struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES);
  460. typedef void (^NSURLSessionTaskDidCompleteWithErrorBlock)(id <NSURLSessionTaskDelegate> slf, NSURLSession *session, NSURLSessionTask *task, NSError *error);
  461. NSURLSessionTaskDidCompleteWithErrorBlock undefinedBlock = ^(id <NSURLSessionTaskDelegate> slf, NSURLSession *session, NSURLSessionTask *task, NSError *error) {
  462. [[FLEXNetworkObserver sharedObserver] URLSession:session task:task didCompleteWithError:error delegate:slf];
  463. };
  464. NSURLSessionTaskDidCompleteWithErrorBlock implementationBlock = ^(id <NSURLSessionTaskDelegate> slf, NSURLSession *session, NSURLSessionTask *task, NSError *error) {
  465. [self sniffWithoutDuplicationForObject:session selector:selector sniffingBlock:^{
  466. undefinedBlock(slf, session, task, error);
  467. } originalImplementationBlock:^{
  468. ((void(*)(id, SEL, id, id, id))objc_msgSend)(slf, swizzledSelector, session, task, error);
  469. }];
  470. };
  471. [self replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription implementationBlock:implementationBlock undefinedBlock:undefinedBlock];
  472. }
  473. // Used for overriding AFNetworking behavior
  474. + (void)injectRespondsToSelectorIntoDelegateClass:(Class)cls
  475. {
  476. SEL selector = @selector(respondsToSelector:);
  477. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  478. //Protocol *protocol = @protocol(NSURLSessionTaskDelegate);
  479. Method method = class_getInstanceMethod(cls, selector);
  480. struct objc_method_description methodDescription = *method_getDescription(method);
  481. typedef void (^NSURLSessionTaskDidCompleteWithErrorBlock)(id slf, SEL sel);
  482. BOOL (^undefinedBlock)(id <NSURLSessionTaskDelegate>, SEL) = ^(id slf, SEL sel) {
  483. return YES;
  484. };
  485. BOOL (^implementationBlock)(id <NSURLSessionTaskDelegate>, SEL) = ^(id <NSURLSessionTaskDelegate> slf, SEL sel) {
  486. if (sel == @selector(URLSession:dataTask:didReceiveResponse:completionHandler:)) {
  487. return undefinedBlock(slf, sel);
  488. }
  489. return ((BOOL(*)(id, SEL, SEL))objc_msgSend)(slf, swizzledSelector, sel);
  490. };
  491. [self replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription implementationBlock:implementationBlock undefinedBlock:undefinedBlock];
  492. }
  493. + (void)injectDownloadTaskDidFinishDownloadingIntoDelegateClass:(Class)cls
  494. {
  495. SEL selector = @selector(URLSession:downloadTask:didFinishDownloadingToURL:);
  496. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  497. Protocol *protocol = @protocol(NSURLSessionDownloadDelegate);
  498. struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES);
  499. typedef void (^NSURLSessionDownloadTaskDidFinishDownloadingBlock)(id <NSURLSessionTaskDelegate> slf, NSURLSession *session, NSURLSessionDownloadTask *task, NSURL *location);
  500. NSURLSessionDownloadTaskDidFinishDownloadingBlock undefinedBlock = ^(id <NSURLSessionTaskDelegate> slf, NSURLSession *session, NSURLSessionDownloadTask *task, NSURL *location) {
  501. NSData *data = [NSData dataWithContentsOfFile:location.relativePath];
  502. [[FLEXNetworkObserver sharedObserver] URLSession:session task:task didFinishDownloadingToURL:location data:data delegate:slf];
  503. };
  504. NSURLSessionDownloadTaskDidFinishDownloadingBlock implementationBlock = ^(id <NSURLSessionTaskDelegate> slf, NSURLSession *session, NSURLSessionDownloadTask *task, NSURL *location) {
  505. [self sniffWithoutDuplicationForObject:session selector:selector sniffingBlock:^{
  506. undefinedBlock(slf, session, task, location);
  507. } originalImplementationBlock:^{
  508. ((void(*)(id, SEL, id, id, id))objc_msgSend)(slf, swizzledSelector, session, task, location);
  509. }];
  510. };
  511. [self replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription implementationBlock:implementationBlock undefinedBlock:undefinedBlock];
  512. }
  513. + (void)injectDownloadTaskDidWriteDataIntoDelegateClass:(Class)cls
  514. {
  515. SEL selector = @selector(URLSession:downloadTask:didWriteData:totalBytesWritten:totalBytesExpectedToWrite:);
  516. SEL swizzledSelector = [self swizzledSelectorForSelector:selector];
  517. Protocol *protocol = @protocol(NSURLSessionDownloadDelegate);
  518. struct objc_method_description methodDescription = protocol_getMethodDescription(protocol, selector, NO, YES);
  519. typedef void (^NSURLSessionDownloadTaskDidWriteDataBlock)(id <NSURLSessionTaskDelegate> slf, NSURLSession *session, NSURLSessionDownloadTask *task, int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite);
  520. NSURLSessionDownloadTaskDidWriteDataBlock undefinedBlock = ^(id <NSURLSessionTaskDelegate> slf, NSURLSession *session, NSURLSessionDownloadTask *task, int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite) {
  521. [[FLEXNetworkObserver sharedObserver] URLSession:session downloadTask:task didWriteData:bytesWritten totalBytesWritten:totalBytesWritten totalBytesExpectedToWrite:totalBytesExpectedToWrite delegate:slf];
  522. };
  523. NSURLSessionDownloadTaskDidWriteDataBlock implementationBlock = ^(id <NSURLSessionTaskDelegate> slf, NSURLSession *session, NSURLSessionDownloadTask *task, int64_t bytesWritten, int64_t totalBytesWritten, int64_t totalBytesExpectedToWrite) {
  524. [self sniffWithoutDuplicationForObject:session selector:selector sniffingBlock:^{
  525. undefinedBlock(slf, session, task, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite);
  526. } originalImplementationBlock:^{
  527. ((void(*)(id, SEL, id, id, int64_t, int64_t, int64_t))objc_msgSend)(slf, swizzledSelector, session, task, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite);
  528. }];
  529. };
  530. [self replaceImplementationOfSelector:selector withSelector:swizzledSelector forClass:cls withMethodDescription:methodDescription implementationBlock:implementationBlock undefinedBlock:undefinedBlock];
  531. }
  532. #pragma mark - Initialization
  533. - (id)init
  534. {
  535. self = [super init];
  536. if (!self) {
  537. return nil;
  538. }
  539. _connectionStates = [[NSMutableDictionary alloc] init];
  540. _queue = dispatch_queue_create("com.flex.FLEXNetworkObserver", DISPATCH_QUEUE_SERIAL);
  541. return self;
  542. }
  543. #pragma mark - Private Methods
  544. - (void)performBlock:(dispatch_block_t)block
  545. {
  546. if (self.isEnabled) {
  547. dispatch_async(_queue, block);
  548. }
  549. }
  550. #pragma mark - Private Methods (Connections)
  551. - (FLEXInternalRequestState *)requestStateForConnection:(NSURLConnection *)connection
  552. {
  553. NSValue *key = [NSValue valueWithNonretainedObject:connection];
  554. FLEXInternalRequestState *state = [_connectionStates objectForKey:key];
  555. if (!state) {
  556. state = [[FLEXInternalRequestState alloc] init];
  557. state.requestID = [[self class] nextRequestID];
  558. [_connectionStates setObject:state forKey:key];
  559. }
  560. return state;
  561. }
  562. - (NSString *)requestIDForConnection:(NSURLConnection *)connection
  563. {
  564. return [self requestStateForConnection:connection].requestID;
  565. }
  566. - (void)setRequest:(NSURLRequest *)request forConnection:(NSURLConnection *)connection
  567. {
  568. [self requestStateForConnection:connection].request = request;
  569. }
  570. - (NSURLRequest *)requestForConnection:(NSURLConnection *)connection
  571. {
  572. return [self requestStateForConnection:connection].request;
  573. }
  574. - (void)setAccumulatedData:(NSMutableData *)data forConnection:(NSURLConnection *)connection
  575. {
  576. FLEXInternalRequestState *requestState = [self requestStateForConnection:connection];
  577. requestState.dataAccumulator = data;
  578. }
  579. - (void)addAccumulatedData:(NSData *)data forConnection:(NSURLConnection *)connection
  580. {
  581. NSMutableData *dataAccumulator = [self requestStateForConnection:connection].dataAccumulator;
  582. [dataAccumulator appendData:data];
  583. }
  584. - (NSData *)accumulatedDataForConnection:(NSURLConnection *)connection
  585. {
  586. return [self requestStateForConnection:connection].dataAccumulator;
  587. }
  588. // This removes storing the accumulated request/response from the dictionary so we can release connection
  589. - (void)connectionFinished:(NSURLConnection *)connection
  590. {
  591. NSValue *key = [NSValue valueWithNonretainedObject:connection];
  592. [_connectionStates removeObjectForKey:key];
  593. }
  594. #pragma mark - Private Methods (Tasks)
  595. - (FLEXInternalRequestState *)requestStateForTask:(NSURLSessionTask *)task
  596. {
  597. NSValue *key = [NSValue valueWithNonretainedObject:task];
  598. FLEXInternalRequestState *state = [_connectionStates objectForKey:key];
  599. if (!state) {
  600. state = [[FLEXInternalRequestState alloc] init];
  601. state.requestID = [[self class] nextRequestID];
  602. [_connectionStates setObject:state forKey:key];
  603. }
  604. return state;
  605. }
  606. - (void)setRequestState:(FLEXInternalRequestState *)state forTask:(NSURLSessionTask *)task
  607. {
  608. NSValue *key = [NSValue valueWithNonretainedObject:task];
  609. [_connectionStates setObject:state forKey:key];
  610. }
  611. - (NSString *)requestIDForTask:(NSURLSessionTask *)task
  612. {
  613. return [self requestStateForTask:task].requestID;
  614. }
  615. - (void)setRequest:(NSURLRequest *)request forTask:(NSURLSessionTask *)task
  616. {
  617. [self requestStateForTask:task].request = request;
  618. }
  619. - (NSURLRequest *)requestForTask:(NSURLSessionTask *)task
  620. {
  621. return [self requestStateForTask:task].request;
  622. }
  623. - (void)setAccumulatedData:(NSMutableData *)data forTask:(NSURLSessionTask *)task
  624. {
  625. FLEXInternalRequestState *requestState = [self requestStateForTask:task];
  626. requestState.dataAccumulator = data;
  627. }
  628. - (void)addAccumulatedData:(NSData *)data forTask:(NSURLSessionTask *)task
  629. {
  630. NSMutableData *dataAccumulator = [self requestStateForTask:task].dataAccumulator;
  631. [dataAccumulator appendData:data];
  632. }
  633. - (NSData *)accumulatedDataForTask:(NSURLSessionTask *)task
  634. {
  635. return [self requestStateForTask:task].dataAccumulator;
  636. }
  637. // This removes storing the accumulated request/response from the dictionary so we can release task
  638. - (void)taskFinished:(NSURLSessionTask *)task
  639. {
  640. NSValue *key = [NSValue valueWithNonretainedObject:task];
  641. [_connectionStates removeObjectForKey:key];
  642. }
  643. @end
  644. @implementation FLEXNetworkObserver (NSURLConnectionHelpers)
  645. - (void)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response delegate:(id<NSURLConnectionDelegate>)delegate
  646. {
  647. [self performBlock:^{
  648. [self setRequest:request forConnection:connection];
  649. NSString *requestId = [self requestIDForConnection:connection];
  650. [[FLEXNetworkRecorder defaultRecorder] recordRequestWillBeSentWithRequestId:requestId request:request redirectResponse:response];
  651. NSString *mechanism = [NSString stringWithFormat:@"NSURLConnection (delegate: %@)", [delegate class]];
  652. [[FLEXNetworkRecorder defaultRecorder] recordMechanism:mechanism forRequestId:requestId];
  653. }];
  654. }
  655. - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response delegate:(id<NSURLConnectionDelegate>)delegate
  656. {
  657. [self performBlock:^{
  658. // If the request wasn't generated yet, then willSendRequest was not called. This appears to be an inconsistency in documentation
  659. // and behavior.
  660. NSURLRequest *request = [self requestForConnection:connection];
  661. if (!request) {
  662. request = connection.currentRequest;
  663. [self setRequest:request forConnection:connection];
  664. [[FLEXNetworkRecorder defaultRecorder] recordRequestWillBeSentWithRequestId:[self requestIDForConnection:connection] request:request redirectResponse:nil];
  665. }
  666. NSMutableData *dataAccumulator = nil;
  667. if (response.expectedContentLength < 0) {
  668. dataAccumulator = [[NSMutableData alloc] init];
  669. } else {
  670. dataAccumulator = [[NSMutableData alloc] initWithCapacity:(NSUInteger)response.expectedContentLength];
  671. }
  672. [self setAccumulatedData:dataAccumulator forConnection:connection];
  673. NSString *requestID = [self requestIDForConnection:connection];
  674. [[FLEXNetworkRecorder defaultRecorder] recordResponseReceivedWithRequestId:requestID response:response];
  675. }];
  676. }
  677. - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data delegate:(id<NSURLConnectionDelegate>)delegate
  678. {
  679. // Just to be safe since we're doing this async
  680. data = [data copy];
  681. [self performBlock:^{
  682. [self addAccumulatedData:data forConnection:connection];
  683. if ([self accumulatedDataForConnection:connection] == nil) return;
  684. NSString *requestID = [self requestIDForConnection:connection];
  685. [[FLEXNetworkRecorder defaultRecorder] recordDataReceivedWithRequestId:requestID dataLength:data.length];
  686. }];
  687. }
  688. - (void)connectionDidFinishLoading:(NSURLConnection *)connection delegate:(id<NSURLConnectionDelegate>)delegate
  689. {
  690. [self performBlock:^{
  691. NSString *requestID = [self requestIDForConnection:connection];
  692. NSData *accumulatedData = [self accumulatedDataForConnection:connection];
  693. [[FLEXNetworkRecorder defaultRecorder] recordLoadingFinishedWithRequestId:requestID responseBody:accumulatedData];
  694. [self connectionFinished:connection];
  695. }];
  696. }
  697. - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error delegate:(id<NSURLConnectionDelegate>)delegate
  698. {
  699. [self performBlock:^{
  700. NSString *requestID = [self requestIDForConnection:connection];
  701. // Cancellations can occur prior to the willSendRequest:... NSURLConnection delegate call.
  702. // These are pretty common and clutter up the logs. Only record the failure if the recorder already knows about the request through willSendRequest:...
  703. if ([self requestForConnection:connection]) {
  704. [[FLEXNetworkRecorder defaultRecorder] recordLoadingFailedWithRequestId:requestID error:error];
  705. }
  706. [self connectionFinished:connection];
  707. }];
  708. }
  709. - (void)connectionWillCancel:(NSURLConnection *)connection
  710. {
  711. [self performBlock:^{
  712. // Mimic the behavior of NSURLSession which is to create an error on cancellation.
  713. NSDictionary *userInfo = @{ NSLocalizedDescriptionKey : @"cancelled" };
  714. NSError *error = [NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorCancelled userInfo:userInfo];
  715. [self connection:connection didFailWithError:error delegate:nil];
  716. }];
  717. }
  718. @end
  719. @implementation FLEXNetworkObserver (NSURLSessionTaskHelpers)
  720. - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task willPerformHTTPRedirection:(NSHTTPURLResponse *)response newRequest:(NSURLRequest *)request completionHandler:(void (^)(NSURLRequest *))completionHandler delegate:(id<NSURLSessionDelegate>)delegate
  721. {
  722. [self performBlock:^{
  723. [self setRequest:request forTask:task];
  724. [[FLEXNetworkRecorder defaultRecorder] recordRequestWillBeSentWithRequestId:[self requestIDForTask:task] request:request redirectResponse:response];
  725. }];
  726. }
  727. - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition disposition))completionHandler delegate:(id<NSURLSessionDelegate>)delegate
  728. {
  729. [self performBlock:^{
  730. // willSendRequest does not exist in NSURLSession. Here's a workaround.
  731. NSURLRequest *request = [self requestForTask:dataTask];
  732. if (!request) {
  733. request = dataTask.currentRequest;
  734. [self setRequest:request forTask:dataTask];
  735. [[FLEXNetworkRecorder defaultRecorder] recordRequestWillBeSentWithRequestId:[self requestIDForTask:dataTask] request:request redirectResponse:nil];
  736. }
  737. NSMutableData *dataAccumulator = nil;
  738. if (response.expectedContentLength < 0) {
  739. dataAccumulator = [[NSMutableData alloc] init];
  740. } else {
  741. dataAccumulator = [[NSMutableData alloc] initWithCapacity:(NSUInteger)response.expectedContentLength];
  742. }
  743. [self setAccumulatedData:dataAccumulator forTask:dataTask];
  744. NSString *requestID = [self requestIDForTask:dataTask];
  745. NSString *requestMechanism = [NSString stringWithFormat:@"NSURLSessionDataTask (delegate: %@)", [delegate class]];
  746. [[FLEXNetworkRecorder defaultRecorder] recordMechanism:requestMechanism forRequestId:requestID];
  747. [[FLEXNetworkRecorder defaultRecorder] recordResponseReceivedWithRequestId:requestID response:response];
  748. }];
  749. }
  750. - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didBecomeDownloadTask:(NSURLSessionDownloadTask *)downloadTask delegate:(id<NSURLSessionDelegate>)delegate
  751. {
  752. [self performBlock:^{
  753. // Update our internal accounting to reflect the task swap.
  754. FLEXInternalRequestState *state = [self requestStateForTask:dataTask];
  755. [self setRequestState:state forTask:downloadTask];
  756. [self taskFinished:dataTask];
  757. }];
  758. }
  759. - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data delegate:(id<NSURLSessionDelegate>)delegate
  760. {
  761. // Just to be safe since we're doing this async
  762. data = [data copy];
  763. [self performBlock:^{
  764. [self addAccumulatedData:data forTask:dataTask];
  765. if ([self accumulatedDataForTask:dataTask] == nil) return;
  766. NSString *requestID = [self requestIDForTask:dataTask];
  767. [[FLEXNetworkRecorder defaultRecorder] recordDataReceivedWithRequestId:requestID dataLength:data.length];
  768. }];
  769. }
  770. - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error delegate:(id<NSURLSessionDelegate>)delegate
  771. {
  772. [self performBlock:^{
  773. NSString *requestID = [self requestIDForTask:task];
  774. NSData *accumulatedData = [self accumulatedDataForTask:task];
  775. if (error) {
  776. [[FLEXNetworkRecorder defaultRecorder] recordLoadingFailedWithRequestId:requestID error:error];
  777. } else {
  778. [[FLEXNetworkRecorder defaultRecorder] recordLoadingFinishedWithRequestId:requestID responseBody:accumulatedData];
  779. }
  780. [self taskFinished:task];
  781. }];
  782. }
  783. - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite delegate:(id<NSURLSessionDelegate>)delegate
  784. {
  785. [self performBlock:^{
  786. NSString *requestID = [self requestIDForTask:downloadTask];
  787. if (![[self requestStateForTask:downloadTask] dataAccumulator]) {
  788. NSMutableData *dataAccumulator = [[NSMutableData alloc] initWithCapacity:(NSUInteger)totalBytesExpectedToWrite];
  789. [self setAccumulatedData:dataAccumulator forTask:downloadTask];
  790. [[FLEXNetworkRecorder defaultRecorder] recordResponseReceivedWithRequestId:requestID response:downloadTask.response];
  791. }
  792. NSString *requestMechanism = [NSString stringWithFormat:@"NSURLSessionDownloadTask (delegate: %@)", [delegate class]];
  793. [[FLEXNetworkRecorder defaultRecorder] recordMechanism:requestMechanism forRequestId:requestID];
  794. [[FLEXNetworkRecorder defaultRecorder] recordDataReceivedWithRequestId:requestID dataLength:bytesWritten];
  795. }];
  796. }
  797. - (void)URLSession:(NSURLSession *)session task:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location data:(NSData *)data delegate:(id<NSURLSessionDelegate>)delegate
  798. {
  799. data = [data copy];
  800. [self performBlock:^{
  801. [self addAccumulatedData:data forTask:downloadTask];
  802. }];
  803. }
  804. - (void)URLSessionTaskWillResume:(NSURLSessionTask *)task
  805. {
  806. // Since resume can be called multiple times on the same task, only treat the first resume as
  807. // the equivalent to connection:willSendRequest:...
  808. [self performBlock:^{
  809. NSURLRequest *request = [self requestForTask:task];
  810. if (!request) {
  811. request = task.currentRequest;
  812. [self setRequest:request forTask:task];
  813. NSString *requestID = [self requestIDForTask:task];
  814. [[FLEXNetworkRecorder defaultRecorder] recordRequestWillBeSentWithRequestId:requestID request:request redirectResponse:nil];
  815. }
  816. }];
  817. }
  818. @end