FLEXNetworkHistoryTableViewController.m 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  1. //
  2. // FLEXNetworkHistoryTableViewController.m
  3. // Flipboard
  4. //
  5. // Created by Ryan Olson on 2/8/15.
  6. // Copyright (c) 2015 Flipboard. All rights reserved.
  7. //
  8. #import "FLEXColor.h"
  9. #import "FLEXUtility.h"
  10. #import "FLEXNetworkHistoryTableViewController.h"
  11. #import "FLEXNetworkTransaction.h"
  12. #import "FLEXNetworkTransactionTableViewCell.h"
  13. #import "FLEXNetworkRecorder.h"
  14. #import "FLEXNetworkTransactionDetailTableViewController.h"
  15. #import "FLEXNetworkObserver.h"
  16. #import "FLEXNetworkSettingsTableViewController.h"
  17. @interface FLEXNetworkHistoryTableViewController ()
  18. /// Backing model
  19. @property (nonatomic, copy) NSArray<FLEXNetworkTransaction *> *networkTransactions;
  20. @property (nonatomic) long long bytesReceived;
  21. @property (nonatomic, copy) NSArray<FLEXNetworkTransaction *> *filteredNetworkTransactions;
  22. @property (nonatomic) long long filteredBytesReceived;
  23. @property (nonatomic) BOOL rowInsertInProgress;
  24. @property (nonatomic) BOOL isPresentingSearch;
  25. @end
  26. @implementation FLEXNetworkHistoryTableViewController
  27. - (id)init
  28. {
  29. self = [super initWithStyle:UITableViewStylePlain];
  30. if (self) {
  31. [NSNotificationCenter.defaultCenter addObserver:self selector:@selector(handleNewTransactionRecordedNotification:) name:kFLEXNetworkRecorderNewTransactionNotification object:nil];
  32. [NSNotificationCenter.defaultCenter addObserver:self selector:@selector(handleTransactionUpdatedNotification:) name:kFLEXNetworkRecorderTransactionUpdatedNotification object:nil];
  33. [NSNotificationCenter.defaultCenter addObserver:self selector:@selector(handleTransactionsClearedNotification:) name:kFLEXNetworkRecorderTransactionsClearedNotification object:nil];
  34. [NSNotificationCenter.defaultCenter addObserver:self selector:@selector(handleNetworkObserverEnabledStateChangedNotification:) name:kFLEXNetworkObserverEnabledStateChangedNotification object:nil];
  35. self.title = @"📡 Network";
  36. self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Settings" style:UIBarButtonItemStylePlain target:self action:@selector(settingsButtonTapped:)];
  37. // Needed to avoid search bar showing over detail pages pushed on the nav stack
  38. // see https://asciiwwdc.com/2014/sessions/228
  39. self.definesPresentationContext = YES;
  40. }
  41. return self;
  42. }
  43. - (void)dealloc
  44. {
  45. [NSNotificationCenter.defaultCenter removeObserver:self];
  46. }
  47. - (void)viewDidLoad
  48. {
  49. [super viewDidLoad];
  50. self.showsSearchBar = YES;
  51. [self.tableView
  52. registerClass:[FLEXNetworkTransactionTableViewCell class]
  53. forCellReuseIdentifier:kFLEXNetworkTransactionCellIdentifier
  54. ];
  55. self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
  56. self.tableView.rowHeight = [FLEXNetworkTransactionTableViewCell preferredCellHeight];
  57. [self updateTransactions];
  58. }
  59. - (void)settingsButtonTapped:(id)sender
  60. {
  61. FLEXNetworkSettingsTableViewController *settingsViewController = [FLEXNetworkSettingsTableViewController new];
  62. settingsViewController.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(settingsViewControllerDoneTapped:)];
  63. settingsViewController.title = @"Network Debugging Settings";
  64. // This is not a FLEXNavigationController because it is not intended as a new tab
  65. UINavigationController *wrapperNavigationController = [[UINavigationController alloc] initWithRootViewController:settingsViewController];
  66. [self presentViewController:wrapperNavigationController animated:YES completion:nil];
  67. }
  68. - (void)settingsViewControllerDoneTapped:(id)sender
  69. {
  70. [self dismissViewControllerAnimated:YES completion:nil];
  71. }
  72. - (void)updateTransactions
  73. {
  74. self.networkTransactions = [[FLEXNetworkRecorder defaultRecorder] networkTransactions];
  75. }
  76. - (void)setNetworkTransactions:(NSArray<FLEXNetworkTransaction *> *)networkTransactions
  77. {
  78. if (![_networkTransactions isEqual:networkTransactions]) {
  79. _networkTransactions = networkTransactions;
  80. [self updateBytesReceived];
  81. [self updateFilteredBytesReceived];
  82. }
  83. }
  84. - (void)updateBytesReceived
  85. {
  86. long long bytesReceived = 0;
  87. for (FLEXNetworkTransaction *transaction in self.networkTransactions) {
  88. bytesReceived += transaction.receivedDataLength;
  89. }
  90. self.bytesReceived = bytesReceived;
  91. [self updateFirstSectionHeader];
  92. }
  93. - (void)setFilteredNetworkTransactions:(NSArray<FLEXNetworkTransaction *> *)filteredNetworkTransactions
  94. {
  95. if (![_filteredNetworkTransactions isEqual:filteredNetworkTransactions]) {
  96. _filteredNetworkTransactions = filteredNetworkTransactions;
  97. [self updateFilteredBytesReceived];
  98. }
  99. }
  100. - (void)updateFilteredBytesReceived
  101. {
  102. long long filteredBytesReceived = 0;
  103. for (FLEXNetworkTransaction *transaction in self.filteredNetworkTransactions) {
  104. filteredBytesReceived += transaction.receivedDataLength;
  105. }
  106. self.filteredBytesReceived = filteredBytesReceived;
  107. [self updateFirstSectionHeader];
  108. }
  109. - (void)updateFirstSectionHeader
  110. {
  111. UIView *view = [self.tableView headerViewForSection:0];
  112. if ([view isKindOfClass:[UITableViewHeaderFooterView class]]) {
  113. UITableViewHeaderFooterView *headerView = (UITableViewHeaderFooterView *)view;
  114. headerView.textLabel.text = [self headerText];
  115. [headerView setNeedsLayout];
  116. }
  117. }
  118. - (NSString *)headerText
  119. {
  120. NSString *headerText = nil;
  121. if (FLEXNetworkObserver.isEnabled) {
  122. long long bytesReceived = 0;
  123. NSInteger totalRequests = 0;
  124. if (self.searchController.isActive) {
  125. bytesReceived = self.filteredBytesReceived;
  126. totalRequests = self.filteredNetworkTransactions.count;
  127. } else {
  128. bytesReceived = self.bytesReceived;
  129. totalRequests = self.networkTransactions.count;
  130. }
  131. NSString *byteCountText = [NSByteCountFormatter stringFromByteCount:bytesReceived countStyle:NSByteCountFormatterCountStyleBinary];
  132. NSString *requestsText = totalRequests == 1 ? @"Request" : @"Requests";
  133. headerText = [NSString stringWithFormat:@"%ld %@ (%@ received)", (long)totalRequests, requestsText, byteCountText];
  134. } else {
  135. headerText = @"⚠️ Debugging Disabled (Enable in Settings)";
  136. }
  137. return headerText;
  138. }
  139. #pragma mark - FLEXGlobalsEntry
  140. + (NSString *)globalsEntryTitle:(FLEXGlobalsRow)row {
  141. return @"📡 Network History";
  142. }
  143. + (UIViewController *)globalsEntryViewController:(FLEXGlobalsRow)row {
  144. return [self new];
  145. }
  146. #pragma mark - Notification Handlers
  147. - (void)handleNewTransactionRecordedNotification:(NSNotification *)notification
  148. {
  149. if (self.viewIfLoaded.window) {
  150. [self tryUpdateTransactions];
  151. }
  152. }
  153. - (void)tryUpdateTransactions
  154. {
  155. // Let the previous row insert animation finish before starting a new one to avoid stomping.
  156. // We'll try calling the method again when the insertion completes, and we properly no-op if there haven't been changes.
  157. if (self.rowInsertInProgress) {
  158. return;
  159. }
  160. if (self.searchController.isActive) {
  161. [self updateTransactions];
  162. [self updateSearchResults:nil];
  163. return;
  164. }
  165. NSInteger existingRowCount = self.networkTransactions.count;
  166. [self updateTransactions];
  167. NSInteger newRowCount = self.networkTransactions.count;
  168. NSInteger addedRowCount = newRowCount - existingRowCount;
  169. if (addedRowCount != 0 && !self.isPresentingSearch) {
  170. // Insert animation if we're at the top.
  171. if (self.tableView.contentOffset.y <= 0.0 && addedRowCount > 0) {
  172. [CATransaction begin];
  173. self.rowInsertInProgress = YES;
  174. [CATransaction setCompletionBlock:^{
  175. self.rowInsertInProgress = NO;
  176. [self tryUpdateTransactions];
  177. }];
  178. NSMutableArray<NSIndexPath *> *indexPathsToReload = [NSMutableArray array];
  179. for (NSInteger row = 0; row < addedRowCount; row++) {
  180. [indexPathsToReload addObject:[NSIndexPath indexPathForRow:row inSection:0]];
  181. }
  182. [self.tableView insertRowsAtIndexPaths:indexPathsToReload withRowAnimation:UITableViewRowAnimationAutomatic];
  183. [CATransaction commit];
  184. } else {
  185. // Maintain the user's position if they've scrolled down.
  186. CGSize existingContentSize = self.tableView.contentSize;
  187. [self.tableView reloadData];
  188. CGFloat contentHeightChange = self.tableView.contentSize.height - existingContentSize.height;
  189. self.tableView.contentOffset = CGPointMake(self.tableView.contentOffset.x, self.tableView.contentOffset.y + contentHeightChange);
  190. }
  191. }
  192. }
  193. - (void)handleTransactionUpdatedNotification:(NSNotification *)notification
  194. {
  195. [self updateBytesReceived];
  196. [self updateFilteredBytesReceived];
  197. FLEXNetworkTransaction *transaction = notification.userInfo[kFLEXNetworkRecorderUserInfoTransactionKey];
  198. // Update both the main table view and search table view if needed.
  199. for (FLEXNetworkTransactionTableViewCell *cell in [self.tableView visibleCells]) {
  200. if ([cell.transaction isEqual:transaction]) {
  201. // Using -[UITableView reloadRowsAtIndexPaths:withRowAnimation:] is overkill here and kicks off a lot of
  202. // work that can make the table view somewhat unresponsive when lots of updates are streaming in.
  203. // We just need to tell the cell that it needs to re-layout.
  204. [cell setNeedsLayout];
  205. break;
  206. }
  207. }
  208. [self updateFirstSectionHeader];
  209. }
  210. - (void)handleTransactionsClearedNotification:(NSNotification *)notification
  211. {
  212. [self updateTransactions];
  213. [self.tableView reloadData];
  214. }
  215. - (void)handleNetworkObserverEnabledStateChangedNotification:(NSNotification *)notification
  216. {
  217. // Update the header, which displays a warning when network debugging is disabled
  218. [self updateFirstSectionHeader];
  219. }
  220. #pragma mark - Table view data source
  221. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  222. {
  223. return self.searchController.isActive ? self.filteredNetworkTransactions.count : self.networkTransactions.count;
  224. }
  225. - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
  226. {
  227. return [self headerText];
  228. }
  229. - (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section
  230. {
  231. if ([view isKindOfClass:[UITableViewHeaderFooterView class]]) {
  232. UITableViewHeaderFooterView *headerView = (UITableViewHeaderFooterView *)view;
  233. headerView.textLabel.font = [UIFont systemFontOfSize:14.0 weight:UIFontWeightSemibold];
  234. }
  235. }
  236. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  237. {
  238. FLEXNetworkTransactionTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kFLEXNetworkTransactionCellIdentifier forIndexPath:indexPath];
  239. cell.transaction = [self transactionAtIndexPath:indexPath];
  240. // Since we insert from the top, assign background colors bottom up to keep them consistent for each transaction.
  241. NSInteger totalRows = [tableView numberOfRowsInSection:indexPath.section];
  242. if ((totalRows - indexPath.row) % 2 == 0) {
  243. cell.backgroundColor = [FLEXColor secondaryBackgroundColor];
  244. } else {
  245. cell.backgroundColor = [FLEXColor primaryBackgroundColor];
  246. }
  247. return cell;
  248. }
  249. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
  250. {
  251. FLEXNetworkTransactionDetailTableViewController *detailViewController = [FLEXNetworkTransactionDetailTableViewController new];
  252. detailViewController.transaction = [self transactionAtIndexPath:indexPath];
  253. [self.navigationController pushViewController:detailViewController animated:YES];
  254. }
  255. #pragma mark - Menu Actions
  256. - (BOOL)tableView:(UITableView *)tableView shouldShowMenuForRowAtIndexPath:(NSIndexPath *)indexPath
  257. {
  258. return YES;
  259. }
  260. - (BOOL)tableView:(UITableView *)tableView canPerformAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender
  261. {
  262. return action == @selector(copy:);
  263. }
  264. - (void)tableView:(UITableView *)tableView performAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender
  265. {
  266. if (action == @selector(copy:)) {
  267. NSURLRequest *request = [self transactionAtIndexPath:indexPath].request;
  268. UIPasteboard.generalPasteboard.string = request.URL.absoluteString ?: @"";
  269. }
  270. }
  271. #if FLEX_AT_LEAST_IOS13_SDK
  272. - (UIContextMenuConfiguration *)tableView:(UITableView *)tableView contextMenuConfigurationForRowAtIndexPath:(NSIndexPath *)indexPath point:(CGPoint)point __IOS_AVAILABLE(13.0)
  273. {
  274. return [UIContextMenuConfiguration
  275. configurationWithIdentifier:nil
  276. previewProvider:nil
  277. actionProvider:^UIMenu *(NSArray<UIMenuElement *> *suggestedActions) {
  278. UIAction *copy = [UIAction
  279. actionWithTitle:@"Copy"
  280. image:nil
  281. identifier:nil
  282. handler:^(__kindof UIAction *action) {
  283. NSURLRequest *request = [self transactionAtIndexPath:indexPath].request;
  284. UIPasteboard.generalPasteboard.string = request.URL.absoluteString ?: @"";
  285. }
  286. ];
  287. return [UIMenu
  288. menuWithTitle:@"" image:nil identifier:nil
  289. options:UIMenuOptionsDisplayInline
  290. children:@[copy]
  291. ];
  292. }
  293. ];
  294. }
  295. #endif
  296. - (FLEXNetworkTransaction *)transactionAtIndexPath:(NSIndexPath *)indexPath
  297. {
  298. return self.searchController.isActive ? self.filteredNetworkTransactions[indexPath.row] : self.networkTransactions[indexPath.row];
  299. }
  300. #pragma mark - Search Bar
  301. - (void)updateSearchResults:(NSString *)searchString
  302. {
  303. [self onBackgroundQueue:^NSArray *{
  304. return [self.networkTransactions filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(FLEXNetworkTransaction *transaction, NSDictionary<NSString *, id> *bindings) {
  305. return [[transaction.request.URL absoluteString] rangeOfString:searchString options:NSCaseInsensitiveSearch].length > 0;
  306. }]];
  307. } thenOnMainQueue:^(NSArray *filteredNetworkTransactions) {
  308. if ([self.searchText isEqual:searchString]) {
  309. self.filteredNetworkTransactions = filteredNetworkTransactions;
  310. [self.tableView reloadData];
  311. }
  312. }];
  313. }
  314. #pragma mark UISearchControllerDelegate
  315. - (void)willPresentSearchController:(UISearchController *)searchController
  316. {
  317. self.isPresentingSearch = YES;
  318. }
  319. - (void)didPresentSearchController:(UISearchController *)searchController
  320. {
  321. self.isPresentingSearch = NO;
  322. }
  323. - (void)willDismissSearchController:(UISearchController *)searchController
  324. {
  325. [self.tableView reloadData];
  326. }
  327. @end