FLEXNetworkHistoryTableViewController.m 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  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, 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. @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 alloc] init];
  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 - Notification Handlers
  135. - (void)handleNewTransactionRecordedNotification:(NSNotification *)notification
  136. {
  137. [self tryUpdateTransactions];
  138. }
  139. - (void)tryUpdateTransactions
  140. {
  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. {
  181. [self updateBytesReceived];
  182. [self updateFilteredBytesReceived];
  183. FLEXNetworkTransaction *transaction = notification.userInfo[kFLEXNetworkRecorderUserInfoTransactionKey];
  184. // Update both the main table view and search table view if needed.
  185. for (FLEXNetworkTransactionTableViewCell *cell in [self.tableView visibleCells]) {
  186. if ([cell.transaction isEqual:transaction]) {
  187. // Using -[UITableView reloadRowsAtIndexPaths:withRowAnimation:] is overkill here and kicks off a lot of
  188. // work that can make the table view somewhat unresponsive when lots of updates are streaming in.
  189. // We just need to tell the cell that it needs to re-layout.
  190. [cell setNeedsLayout];
  191. break;
  192. }
  193. }
  194. [self updateFirstSectionHeader];
  195. }
  196. - (void)handleTransactionsClearedNotification:(NSNotification *)notification
  197. {
  198. [self updateTransactions];
  199. [self.tableView reloadData];
  200. }
  201. - (void)handleNetworkObserverEnabledStateChangedNotification:(NSNotification *)notification
  202. {
  203. // Update the header, which displays a warning when network debugging is disabled
  204. [self updateFirstSectionHeader];
  205. }
  206. #pragma mark - Table view data source
  207. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
  208. {
  209. return 1;
  210. }
  211. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  212. {
  213. return self.searchController.isActive ? [self.filteredNetworkTransactions count] : [self.networkTransactions count];
  214. }
  215. - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
  216. {
  217. return [self headerText];
  218. }
  219. - (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section
  220. {
  221. if ([view isKindOfClass:[UITableViewHeaderFooterView class]]) {
  222. UITableViewHeaderFooterView *headerView = (UITableViewHeaderFooterView *)view;
  223. headerView.textLabel.font = [UIFont systemFontOfSize:14.0 weight:UIFontWeightSemibold];
  224. }
  225. }
  226. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  227. {
  228. FLEXNetworkTransactionTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kFLEXNetworkTransactionCellIdentifier forIndexPath:indexPath];
  229. cell.transaction = [self transactionAtIndexPath:indexPath inTableView:tableView];
  230. // Since we insert from the top, assign background colors bottom up to keep them consistent for each transaction.
  231. NSInteger totalRows = [tableView numberOfRowsInSection:indexPath.section];
  232. if ((totalRows - indexPath.row) % 2 == 0) {
  233. cell.backgroundColor = [FLEXColor secondaryBackgroundColor];
  234. } else {
  235. cell.backgroundColor = [FLEXColor primaryBackgroundColor];
  236. }
  237. return cell;
  238. }
  239. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
  240. {
  241. FLEXNetworkTransactionDetailTableViewController *detailViewController = [[FLEXNetworkTransactionDetailTableViewController alloc] init];
  242. detailViewController.transaction = [self transactionAtIndexPath:indexPath inTableView:tableView];
  243. [self.navigationController pushViewController:detailViewController animated:YES];
  244. }
  245. #pragma mark - Menu Actions
  246. - (BOOL)tableView:(UITableView *)tableView shouldShowMenuForRowAtIndexPath:(NSIndexPath *)indexPath
  247. {
  248. return YES;
  249. }
  250. - (BOOL)tableView:(UITableView *)tableView canPerformAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender
  251. {
  252. return action == @selector(copy:);
  253. }
  254. - (void)tableView:(UITableView *)tableView performAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender
  255. {
  256. if (action == @selector(copy:)) {
  257. FLEXNetworkTransaction *transaction = [self transactionAtIndexPath:indexPath inTableView:tableView];
  258. NSString *requestURLString = transaction.request.URL.absoluteString ?: @"";
  259. [[UIPasteboard generalPasteboard] setString:requestURLString];
  260. }
  261. }
  262. - (FLEXNetworkTransaction *)transactionAtIndexPath:(NSIndexPath *)indexPath inTableView:(UITableView *)tableView
  263. {
  264. return self.searchController.isActive ? self.filteredNetworkTransactions[indexPath.row] : self.networkTransactions[indexPath.row];
  265. }
  266. #pragma mark - Search Bar
  267. - (void)updateSearchResults:(NSString *)searchString
  268. {
  269. [self onBackgroundQueue:^NSArray *{
  270. return [self.networkTransactions filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(FLEXNetworkTransaction *transaction, NSDictionary<NSString *, id> *bindings) {
  271. return [[transaction.request.URL absoluteString] rangeOfString:searchString options:NSCaseInsensitiveSearch].length > 0;
  272. }]];
  273. } thenOnMainQueue:^(NSArray *filteredNetworkTransactions) {
  274. if ([self.searchText isEqual:searchString]) {
  275. self.filteredNetworkTransactions = filteredNetworkTransactions;
  276. [self.tableView reloadData];
  277. }
  278. }];
  279. }
  280. #pragma mark UISearchControllerDelegate
  281. - (void)willPresentSearchController:(UISearchController *)searchController
  282. {
  283. self.isPresentingSearch = YES;
  284. }
  285. - (void)didPresentSearchController:(UISearchController *)searchController
  286. {
  287. self.isPresentingSearch = NO;
  288. }
  289. - (void)willDismissSearchController:(UISearchController *)searchController
  290. {
  291. [self.tableView reloadData];
  292. }
  293. @end