FLEXNetworkHistoryTableViewController.m 14 KB

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