FLEXNetworkHistoryTableViewController.m 14 KB

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