FLEXNetworkHistoryTableViewController.m 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  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 () <UISearchDisplayDelegate>
  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, strong) UISearchDisplayController *searchController;
  23. @end
  24. @implementation FLEXNetworkHistoryTableViewController
  25. - (instancetype)initWithStyle:(UITableViewStyle)style
  26. {
  27. self = [super initWithStyle:style];
  28. if (self) {
  29. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleNewTransactionRecordedNotification:) name:kFLEXNetworkRecorderNewTransactionNotification object:nil];
  30. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleTransactionUpdatedNotification:) name:kFLEXNetworkRecorderTransactionUpdatedNotification object:nil];
  31. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleTransactionsClearedNotification:) name:kFLEXNetworkRecorderTransactionsClearedNotification object:nil];
  32. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleNetworkObserverEnabledStateChangedNotification:) name:kFLEXNetworkObserverEnabledStateChangedNotification object:nil];
  33. self.title = @"📡 Network";
  34. self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Settings" style:UIBarButtonItemStylePlain target:self action:@selector(settingsButtonTapped:)];
  35. }
  36. return self;
  37. }
  38. - (void)dealloc
  39. {
  40. [[NSNotificationCenter defaultCenter] removeObserver:self];
  41. }
  42. - (void)viewDidLoad
  43. {
  44. [super viewDidLoad];
  45. [self.tableView registerClass:[FLEXNetworkTransactionTableViewCell class] forCellReuseIdentifier:kFLEXNetworkTransactionCellIdentifier];
  46. self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
  47. self.tableView.rowHeight = [FLEXNetworkTransactionTableViewCell preferredCellHeight];
  48. UISearchBar *searchBar = [[UISearchBar alloc] init];
  49. [searchBar sizeToFit];
  50. self.searchController = [[UISearchDisplayController alloc] initWithSearchBar:searchBar contentsController:self];
  51. self.searchController.delegate = self;
  52. self.searchController.searchResultsDataSource = self;
  53. self.searchController.searchResultsDelegate = self;
  54. [self.searchController.searchResultsTableView registerClass:[FLEXNetworkTransactionTableViewCell class] forCellReuseIdentifier:kFLEXNetworkTransactionCellIdentifier];
  55. self.searchController.searchResultsTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
  56. self.searchController.searchResultsTableView.rowHeight = [FLEXNetworkTransactionTableViewCell preferredCellHeight];
  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 *)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 updateFirstSectionHeaderInTableView:self.tableView];
  92. }
  93. - (void)setFilteredNetworkTransactions:(NSArray *)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 updateFirstSectionHeaderInTableView:self.searchController.searchResultsTableView];
  108. }
  109. - (void)updateFirstSectionHeaderInTableView:(UITableView *)tableView
  110. {
  111. UIView *view = [tableView headerViewForSection:0];
  112. if ([view isKindOfClass:[UITableViewHeaderFooterView class]]) {
  113. UITableViewHeaderFooterView *headerView = (UITableViewHeaderFooterView *)view;
  114. headerView.textLabel.text = [self headerTextForTableView:tableView];
  115. [headerView setNeedsLayout];
  116. }
  117. }
  118. - (NSString *)headerTextForTableView:(UITableView *)tableView
  119. {
  120. NSString *headerText = nil;
  121. if ([FLEXNetworkObserver isEnabled]) {
  122. long long bytesReceived = 0;
  123. NSInteger totalRequests = 0;
  124. if (tableView == self.tableView) {
  125. bytesReceived = self.bytesReceived;
  126. totalRequests = [self.networkTransactions count];
  127. } else if (tableView == self.searchController.searchResultsTableView) {
  128. bytesReceived = self.filteredBytesReceived;
  129. totalRequests = [self.filteredNetworkTransactions 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. NSInteger existingRowCount = [self.networkTransactions count];
  152. [self updateTransactions];
  153. NSInteger newRowCount = [self.networkTransactions count];
  154. NSInteger addedRowCount = newRowCount - existingRowCount;
  155. if (addedRowCount != 0) {
  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 *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. if (self.searchController.isActive) {
  178. [self updateSearchResultsWithSearchString:self.searchController.searchBar.text];
  179. }
  180. }
  181. }
  182. - (void)handleTransactionUpdatedNotification:(NSNotification *)notification
  183. {
  184. [self updateBytesReceived];
  185. [self updateFilteredBytesReceived];
  186. FLEXNetworkTransaction *transaction = [notification.userInfo objectForKey:kFLEXNetworkRecorderUserInfoTransactionKey];
  187. NSArray *tableViews = @[self.tableView];
  188. if (self.searchController.searchResultsTableView) {
  189. tableViews = [tableViews arrayByAddingObject:self.searchController.searchResultsTableView];
  190. }
  191. // Update both the main table view and search table view if needed.
  192. for (UITableView *tableView in tableViews) {
  193. for (FLEXNetworkTransactionTableViewCell *cell in [tableView visibleCells]) {
  194. if ([cell.transaction isEqual:transaction]) {
  195. NSIndexPath *indexPath = [tableView indexPathForCell:cell];
  196. if (indexPath) {
  197. [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
  198. }
  199. break;
  200. }
  201. }
  202. [self updateFirstSectionHeaderInTableView:tableView];
  203. }
  204. }
  205. - (void)handleTransactionsClearedNotification:(NSNotification *)notification
  206. {
  207. [self updateTransactions];
  208. [self.tableView reloadData];
  209. [self.searchController.searchResultsTableView reloadData];
  210. }
  211. - (void)handleNetworkObserverEnabledStateChangedNotification:(NSNotification *)notification
  212. {
  213. // Update the header, which displays a warning when network debugging is disabled
  214. [self updateFirstSectionHeaderInTableView:self.tableView];
  215. }
  216. #pragma mark - Table view data source
  217. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
  218. {
  219. return 1;
  220. }
  221. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  222. {
  223. NSInteger numberOfRows = 0;
  224. if (tableView == self.tableView) {
  225. numberOfRows = [self.networkTransactions count];
  226. } else if (tableView == self.searchController.searchResultsTableView) {
  227. numberOfRows = [self.filteredNetworkTransactions count];
  228. }
  229. return numberOfRows;
  230. }
  231. - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
  232. {
  233. return [self headerTextForTableView:tableView];
  234. }
  235. - (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section
  236. {
  237. if ([view isKindOfClass:[UITableViewHeaderFooterView class]]) {
  238. UITableViewHeaderFooterView *headerView = (UITableViewHeaderFooterView *)view;
  239. headerView.textLabel.font = [UIFont fontWithName:@"HelveticaNeue-Medium" size:14.0];
  240. headerView.textLabel.textColor = [UIColor whiteColor];
  241. headerView.contentView.backgroundColor = [UIColor colorWithWhite:0.5 alpha:1.0];
  242. }
  243. }
  244. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  245. {
  246. FLEXNetworkTransactionTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kFLEXNetworkTransactionCellIdentifier forIndexPath:indexPath];
  247. cell.transaction = [self transactionAtIndexPath:indexPath inTableView:tableView];
  248. // Since we insert from the top, assign background colors bottom up to keep them consistent for each transaction.
  249. NSInteger totalRows = [tableView numberOfRowsInSection:indexPath.section];
  250. if ((totalRows - indexPath.row) % 2 == 0) {
  251. cell.backgroundColor = [UIColor colorWithWhite:0.95 alpha:1.0];
  252. } else {
  253. cell.backgroundColor = [UIColor whiteColor];
  254. }
  255. return cell;
  256. }
  257. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
  258. {
  259. FLEXNetworkTransactionDetailTableViewController *detailViewController = [[FLEXNetworkTransactionDetailTableViewController alloc] init];
  260. detailViewController.transaction = [self transactionAtIndexPath:indexPath inTableView:tableView];
  261. [self.navigationController pushViewController:detailViewController animated:YES];
  262. }
  263. - (FLEXNetworkTransaction *)transactionAtIndexPath:(NSIndexPath *)indexPath inTableView:(UITableView *)tableView
  264. {
  265. FLEXNetworkTransaction *transaction = nil;
  266. if (tableView == self.tableView) {
  267. transaction = [self.networkTransactions objectAtIndex:indexPath.row];
  268. } else if (tableView == self.searchController.searchResultsTableView) {
  269. transaction = [self.filteredNetworkTransactions objectAtIndex:indexPath.row];
  270. }
  271. return transaction;
  272. }
  273. #pragma mark - Search display delegate
  274. - (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
  275. {
  276. [self updateSearchResultsWithSearchString:searchString];
  277. // Reload done after the data is filtered asynchronously
  278. return NO;
  279. }
  280. - (void)updateSearchResultsWithSearchString:(NSString *)searchString
  281. {
  282. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  283. NSArray *filteredNetworkTransactions = [self.networkTransactions filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(FLEXNetworkTransaction *transaction, NSDictionary *bindings) {
  284. return [[transaction.request.URL absoluteString] rangeOfString:searchString options:NSCaseInsensitiveSearch].length > 0;
  285. }]];
  286. dispatch_async(dispatch_get_main_queue(), ^{
  287. if ([self.searchDisplayController.searchBar.text isEqual:searchString]) {
  288. self.filteredNetworkTransactions = filteredNetworkTransactions;
  289. [self.searchDisplayController.searchResultsTableView reloadData];
  290. }
  291. });
  292. });
  293. }
  294. @end