FLEXNetworkHistoryTableViewController.m 15 KB

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