FLEXNetworkHistoryTableViewController.m 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  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 () <UISearchResultsUpdating, UISearchControllerDelegate>
  17. /// Backing model
  18. @property (nonatomic, copy) NSArray<FLEXNetworkTransaction *> *networkTransactions;
  19. @property (nonatomic, assign) long long bytesReceived;
  20. @property (nonatomic, copy) NSArray<FLEXNetworkTransaction *> *filteredNetworkTransactions;
  21. @property (nonatomic, assign) long long filteredBytesReceived;
  22. @property (nonatomic, assign) BOOL rowInsertInProgress;
  23. @property (nonatomic, assign) BOOL isPresentingSearch;
  24. @property (nonatomic, strong) UISearchController *searchController;
  25. @end
  26. @implementation FLEXNetworkHistoryTableViewController
  27. - (instancetype)initWithStyle:(UITableViewStyle)style
  28. {
  29. self = [super initWithStyle:style];
  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.tableView registerClass:[FLEXNetworkTransactionTableViewCell class] forCellReuseIdentifier:kFLEXNetworkTransactionCellIdentifier];
  51. self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
  52. self.tableView.rowHeight = [FLEXNetworkTransactionTableViewCell preferredCellHeight];
  53. self.searchController = [[UISearchController alloc] initWithSearchResultsController:nil];
  54. self.searchController.delegate = self;
  55. self.searchController.searchResultsUpdater = self;
  56. self.searchController.dimsBackgroundDuringPresentation = NO;
  57. self.tableView.tableHeaderView = self.searchController.searchBar;
  58. [self updateTransactions];
  59. }
  60. - (void)settingsButtonTapped:(id)sender
  61. {
  62. FLEXNetworkSettingsTableViewController *settingsViewController = [[FLEXNetworkSettingsTableViewController alloc] init];
  63. settingsViewController.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(settingsViewControllerDoneTapped:)];
  64. settingsViewController.title = @"Network Debugging Settings";
  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 - Notification Handlers
  140. - (void)handleNewTransactionRecordedNotification:(NSNotification *)notification
  141. {
  142. [self tryUpdateTransactions];
  143. }
  144. - (void)tryUpdateTransactions
  145. {
  146. // Let the previous row insert animation finish before starting a new one to avoid stomping.
  147. // We'll try calling the method again when the insertion completes, and we properly no-op if there haven't been changes.
  148. if (self.rowInsertInProgress) {
  149. return;
  150. }
  151. if (self.searchController.isActive) {
  152. [self updateTransactions];
  153. [self updateSearchResults];
  154. return;
  155. }
  156. NSInteger existingRowCount = [self.networkTransactions count];
  157. [self updateTransactions];
  158. NSInteger newRowCount = [self.networkTransactions count];
  159. NSInteger addedRowCount = newRowCount - existingRowCount;
  160. if (addedRowCount != 0 && !self.isPresentingSearch) {
  161. // Insert animation if we're at the top.
  162. if (self.tableView.contentOffset.y <= 0.0 && addedRowCount > 0) {
  163. [CATransaction begin];
  164. self.rowInsertInProgress = YES;
  165. [CATransaction setCompletionBlock:^{
  166. self.rowInsertInProgress = NO;
  167. [self tryUpdateTransactions];
  168. }];
  169. NSMutableArray<NSIndexPath *> *indexPathsToReload = [NSMutableArray array];
  170. for (NSInteger row = 0; row < addedRowCount; row++) {
  171. [indexPathsToReload addObject:[NSIndexPath indexPathForRow:row inSection:0]];
  172. }
  173. [self.tableView insertRowsAtIndexPaths:indexPathsToReload withRowAnimation:UITableViewRowAnimationAutomatic];
  174. [CATransaction commit];
  175. } else {
  176. // Maintain the user's position if they've scrolled down.
  177. CGSize existingContentSize = self.tableView.contentSize;
  178. [self.tableView reloadData];
  179. CGFloat contentHeightChange = self.tableView.contentSize.height - existingContentSize.height;
  180. self.tableView.contentOffset = CGPointMake(self.tableView.contentOffset.x, self.tableView.contentOffset.y + contentHeightChange);
  181. }
  182. }
  183. }
  184. - (void)handleTransactionUpdatedNotification:(NSNotification *)notification
  185. {
  186. [self updateBytesReceived];
  187. [self updateFilteredBytesReceived];
  188. FLEXNetworkTransaction *transaction = notification.userInfo[kFLEXNetworkRecorderUserInfoTransactionKey];
  189. // Update both the main table view and search table view if needed.
  190. for (FLEXNetworkTransactionTableViewCell *cell in [self.tableView visibleCells]) {
  191. if ([cell.transaction isEqual:transaction]) {
  192. // Using -[UITableView reloadRowsAtIndexPaths:withRowAnimation:] is overkill here and kicks off a lot of
  193. // work that can make the table view somewhat unresponsive when lots of updates are streaming in.
  194. // We just need to tell the cell that it needs to re-layout.
  195. [cell setNeedsLayout];
  196. break;
  197. }
  198. }
  199. [self updateFirstSectionHeader];
  200. }
  201. - (void)handleTransactionsClearedNotification:(NSNotification *)notification
  202. {
  203. [self updateTransactions];
  204. [self.tableView reloadData];
  205. }
  206. - (void)handleNetworkObserverEnabledStateChangedNotification:(NSNotification *)notification
  207. {
  208. // Update the header, which displays a warning when network debugging is disabled
  209. [self updateFirstSectionHeader];
  210. }
  211. #pragma mark - Table view data source
  212. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
  213. {
  214. return 1;
  215. }
  216. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  217. {
  218. return self.searchController.isActive ? [self.filteredNetworkTransactions count] : [self.networkTransactions count];
  219. }
  220. - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
  221. {
  222. return [self headerText];
  223. }
  224. - (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section
  225. {
  226. if ([view isKindOfClass:[UITableViewHeaderFooterView class]]) {
  227. UITableViewHeaderFooterView *headerView = (UITableViewHeaderFooterView *)view;
  228. headerView.textLabel.font = [UIFont fontWithName:@"HelveticaNeue-Medium" size:14.0];
  229. headerView.textLabel.textColor = [UIColor whiteColor];
  230. headerView.contentView.backgroundColor = [UIColor colorWithWhite:0.5 alpha:1.0];
  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 systemBackgroundColor];
  243. }
  244. return cell;
  245. }
  246. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
  247. {
  248. FLEXNetworkTransactionDetailTableViewController *detailViewController = [[FLEXNetworkTransactionDetailTableViewController alloc] init];
  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 - UISearchResultsUpdating
  274. - (void)updateSearchResultsForSearchController:(UISearchController *)searchController
  275. {
  276. [self updateSearchResults];
  277. }
  278. - (void)updateSearchResults
  279. {
  280. NSString *searchString = self.searchController.searchBar.text;
  281. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  282. NSArray<FLEXNetworkTransaction *> *filteredNetworkTransactions = [self.networkTransactions filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(FLEXNetworkTransaction *transaction, NSDictionary<NSString *, id> *bindings) {
  283. return [[transaction.request.URL absoluteString] rangeOfString:searchString options:NSCaseInsensitiveSearch].length > 0;
  284. }]];
  285. dispatch_async(dispatch_get_main_queue(), ^{
  286. if ([self.searchController.searchBar.text isEqual:searchString]) {
  287. self.filteredNetworkTransactions = filteredNetworkTransactions;
  288. [self.tableView reloadData];
  289. }
  290. });
  291. });
  292. }
  293. #pragma mark - UISearchControllerDelegate
  294. - (void)willPresentSearchController:(UISearchController *)searchController
  295. {
  296. self.isPresentingSearch = YES;
  297. }
  298. - (void)didPresentSearchController:(UISearchController *)searchController
  299. {
  300. self.isPresentingSearch = NO;
  301. }
  302. - (void)willDismissSearchController:(UISearchController *)searchController
  303. {
  304. [self.tableView reloadData];
  305. }
  306. @end