FLEXNetworkHistoryTableViewController.m 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  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. #pragma clang diagnostic push
  23. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  24. @property (nonatomic, strong) UISearchDisplayController *searchController;
  25. #pragma clang diagnostic pop
  26. @end
  27. @implementation FLEXNetworkHistoryTableViewController
  28. - (instancetype)initWithStyle:(UITableViewStyle)style
  29. {
  30. self = [super initWithStyle:style];
  31. if (self) {
  32. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleNewTransactionRecordedNotification:) name:kFLEXNetworkRecorderNewTransactionNotification object:nil];
  33. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleTransactionUpdatedNotification:) name:kFLEXNetworkRecorderTransactionUpdatedNotification object:nil];
  34. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleTransactionsClearedNotification:) name:kFLEXNetworkRecorderTransactionsClearedNotification object:nil];
  35. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleNetworkObserverEnabledStateChangedNotification:) name:kFLEXNetworkObserverEnabledStateChangedNotification object:nil];
  36. self.title = @"📡 Network";
  37. self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Settings" style:UIBarButtonItemStylePlain target:self action:@selector(settingsButtonTapped:)];
  38. }
  39. return self;
  40. }
  41. - (void)dealloc
  42. {
  43. [[NSNotificationCenter defaultCenter] removeObserver:self];
  44. }
  45. - (void)viewDidLoad
  46. {
  47. [super viewDidLoad];
  48. [self.tableView registerClass:[FLEXNetworkTransactionTableViewCell class] forCellReuseIdentifier:kFLEXNetworkTransactionCellIdentifier];
  49. self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
  50. self.tableView.rowHeight = [FLEXNetworkTransactionTableViewCell preferredCellHeight];
  51. UISearchBar *searchBar = [[UISearchBar alloc] init];
  52. [searchBar sizeToFit];
  53. self.searchController = [[UISearchDisplayController alloc] initWithSearchBar:searchBar contentsController:self];
  54. self.searchController.delegate = self;
  55. self.searchController.searchResultsDataSource = self;
  56. self.searchController.searchResultsDelegate = self;
  57. [self.searchController.searchResultsTableView registerClass:[FLEXNetworkTransactionTableViewCell class] forCellReuseIdentifier:kFLEXNetworkTransactionCellIdentifier];
  58. self.searchController.searchResultsTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
  59. self.searchController.searchResultsTableView.rowHeight = [FLEXNetworkTransactionTableViewCell preferredCellHeight];
  60. self.tableView.tableHeaderView = self.searchController.searchBar;
  61. [self updateTransactions];
  62. }
  63. - (void)settingsButtonTapped:(id)sender
  64. {
  65. FLEXNetworkSettingsTableViewController *settingsViewController = [[FLEXNetworkSettingsTableViewController alloc] init];
  66. settingsViewController.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(settingsViewControllerDoneTapped:)];
  67. settingsViewController.title = @"Network Debugging Settings";
  68. UINavigationController *wrapperNavigationController = [[UINavigationController alloc] initWithRootViewController:settingsViewController];
  69. [self presentViewController:wrapperNavigationController animated:YES completion:nil];
  70. }
  71. - (void)settingsViewControllerDoneTapped:(id)sender
  72. {
  73. [self dismissViewControllerAnimated:YES completion:nil];
  74. }
  75. - (void)updateTransactions
  76. {
  77. self.networkTransactions = [[FLEXNetworkRecorder defaultRecorder] networkTransactions];
  78. }
  79. - (void)setNetworkTransactions:(NSArray *)networkTransactions
  80. {
  81. if (![_networkTransactions isEqual:networkTransactions]) {
  82. _networkTransactions = networkTransactions;
  83. [self updateBytesReceived];
  84. [self updateFilteredBytesReceived];
  85. }
  86. }
  87. - (void)updateBytesReceived
  88. {
  89. long long bytesReceived = 0;
  90. for (FLEXNetworkTransaction *transaction in self.networkTransactions) {
  91. bytesReceived += transaction.receivedDataLength;
  92. }
  93. self.bytesReceived = bytesReceived;
  94. [self updateFirstSectionHeaderInTableView:self.tableView];
  95. }
  96. - (void)setFilteredNetworkTransactions:(NSArray *)filteredNetworkTransactions
  97. {
  98. if (![_filteredNetworkTransactions isEqual:filteredNetworkTransactions]) {
  99. _filteredNetworkTransactions = filteredNetworkTransactions;
  100. [self updateFilteredBytesReceived];
  101. }
  102. }
  103. - (void)updateFilteredBytesReceived
  104. {
  105. long long filteredBytesReceived = 0;
  106. for (FLEXNetworkTransaction *transaction in self.filteredNetworkTransactions) {
  107. filteredBytesReceived += transaction.receivedDataLength;
  108. }
  109. self.filteredBytesReceived = filteredBytesReceived;
  110. [self updateFirstSectionHeaderInTableView:self.searchController.searchResultsTableView];
  111. }
  112. - (void)updateFirstSectionHeaderInTableView:(UITableView *)tableView
  113. {
  114. UIView *view = [tableView headerViewForSection:0];
  115. if ([view isKindOfClass:[UITableViewHeaderFooterView class]]) {
  116. UITableViewHeaderFooterView *headerView = (UITableViewHeaderFooterView *)view;
  117. headerView.textLabel.text = [self headerTextForTableView:tableView];
  118. [headerView setNeedsLayout];
  119. }
  120. }
  121. - (NSString *)headerTextForTableView:(UITableView *)tableView
  122. {
  123. NSString *headerText = nil;
  124. if ([FLEXNetworkObserver isEnabled]) {
  125. long long bytesReceived = 0;
  126. NSInteger totalRequests = 0;
  127. if (tableView == self.tableView) {
  128. bytesReceived = self.bytesReceived;
  129. totalRequests = [self.networkTransactions count];
  130. } else if (tableView == self.searchController.searchResultsTableView) {
  131. bytesReceived = self.filteredBytesReceived;
  132. totalRequests = [self.filteredNetworkTransactions count];
  133. }
  134. NSString *byteCountText = [NSByteCountFormatter stringFromByteCount:bytesReceived countStyle:NSByteCountFormatterCountStyleBinary];
  135. NSString *requestsText = totalRequests == 1 ? @"Request" : @"Requests";
  136. headerText = [NSString stringWithFormat:@"%ld %@ (%@ received)", (long)totalRequests, requestsText, byteCountText];
  137. } else {
  138. headerText = @"⚠️ Debugging Disabled (Enable in Settings)";
  139. }
  140. return headerText;
  141. }
  142. #pragma mark - Notification Handlers
  143. - (void)handleNewTransactionRecordedNotification:(NSNotification *)notification
  144. {
  145. [self tryUpdateTransactions];
  146. }
  147. - (void)tryUpdateTransactions
  148. {
  149. // Let the previous row insert animation finish before starting a new one to avoid stomping.
  150. // We'll try calling the method again when the insertion completes, and we properly no-op if there haven't been changes.
  151. if (self.rowInsertInProgress) {
  152. return;
  153. }
  154. NSInteger existingRowCount = [self.networkTransactions count];
  155. [self updateTransactions];
  156. NSInteger newRowCount = [self.networkTransactions count];
  157. NSInteger addedRowCount = newRowCount - existingRowCount;
  158. if (addedRowCount != 0) {
  159. // Insert animation if we're at the top.
  160. if (self.tableView.contentOffset.y <= 0.0 && addedRowCount > 0) {
  161. [CATransaction begin];
  162. self.rowInsertInProgress = YES;
  163. [CATransaction setCompletionBlock:^{
  164. self.rowInsertInProgress = NO;
  165. [self tryUpdateTransactions];
  166. }];
  167. NSMutableArray *indexPathsToReload = [NSMutableArray array];
  168. for (NSInteger row = 0; row < addedRowCount; row++) {
  169. [indexPathsToReload addObject:[NSIndexPath indexPathForRow:row inSection:0]];
  170. }
  171. [self.tableView insertRowsAtIndexPaths:indexPathsToReload withRowAnimation:UITableViewRowAnimationAutomatic];
  172. [CATransaction commit];
  173. } else {
  174. // Maintain the user's position if they've scrolled down.
  175. CGSize existingContentSize = self.tableView.contentSize;
  176. [self.tableView reloadData];
  177. CGFloat contentHeightChange = self.tableView.contentSize.height - existingContentSize.height;
  178. self.tableView.contentOffset = CGPointMake(self.tableView.contentOffset.x, self.tableView.contentOffset.y + contentHeightChange);
  179. }
  180. if (self.searchController.isActive) {
  181. [self updateSearchResultsWithSearchString:self.searchController.searchBar.text];
  182. }
  183. }
  184. }
  185. - (void)handleTransactionUpdatedNotification:(NSNotification *)notification
  186. {
  187. [self updateBytesReceived];
  188. [self updateFilteredBytesReceived];
  189. FLEXNetworkTransaction *transaction = [notification.userInfo objectForKey:kFLEXNetworkRecorderUserInfoTransactionKey];
  190. NSArray *tableViews = @[self.tableView];
  191. if (self.searchController.searchResultsTableView) {
  192. tableViews = [tableViews arrayByAddingObject:self.searchController.searchResultsTableView];
  193. }
  194. // Update both the main table view and search table view if needed.
  195. for (UITableView *tableView in tableViews) {
  196. for (FLEXNetworkTransactionTableViewCell *cell in [tableView visibleCells]) {
  197. if ([cell.transaction isEqual:transaction]) {
  198. NSIndexPath *indexPath = [tableView indexPathForCell:cell];
  199. if (indexPath) {
  200. [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
  201. }
  202. break;
  203. }
  204. }
  205. [self updateFirstSectionHeaderInTableView:tableView];
  206. }
  207. }
  208. - (void)handleTransactionsClearedNotification:(NSNotification *)notification
  209. {
  210. [self updateTransactions];
  211. [self.tableView reloadData];
  212. [self.searchController.searchResultsTableView reloadData];
  213. }
  214. - (void)handleNetworkObserverEnabledStateChangedNotification:(NSNotification *)notification
  215. {
  216. // Update the header, which displays a warning when network debugging is disabled
  217. [self updateFirstSectionHeaderInTableView:self.tableView];
  218. }
  219. #pragma mark - Table view data source
  220. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
  221. {
  222. return 1;
  223. }
  224. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  225. {
  226. NSInteger numberOfRows = 0;
  227. if (tableView == self.tableView) {
  228. numberOfRows = [self.networkTransactions count];
  229. } else if (tableView == self.searchController.searchResultsTableView) {
  230. numberOfRows = [self.filteredNetworkTransactions count];
  231. }
  232. return numberOfRows;
  233. }
  234. - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
  235. {
  236. return [self headerTextForTableView:tableView];
  237. }
  238. - (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section
  239. {
  240. if ([view isKindOfClass:[UITableViewHeaderFooterView class]]) {
  241. UITableViewHeaderFooterView *headerView = (UITableViewHeaderFooterView *)view;
  242. headerView.textLabel.font = [UIFont fontWithName:@"HelveticaNeue-Medium" size:14.0];
  243. headerView.textLabel.textColor = [UIColor whiteColor];
  244. headerView.contentView.backgroundColor = [UIColor colorWithWhite:0.5 alpha:1.0];
  245. }
  246. }
  247. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  248. {
  249. FLEXNetworkTransactionTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kFLEXNetworkTransactionCellIdentifier forIndexPath:indexPath];
  250. cell.transaction = [self transactionAtIndexPath:indexPath inTableView:tableView];
  251. // Since we insert from the top, assign background colors bottom up to keep them consistent for each transaction.
  252. NSInteger totalRows = [tableView numberOfRowsInSection:indexPath.section];
  253. if ((totalRows - indexPath.row) % 2 == 0) {
  254. cell.backgroundColor = [UIColor colorWithWhite:0.95 alpha:1.0];
  255. } else {
  256. cell.backgroundColor = [UIColor whiteColor];
  257. }
  258. return cell;
  259. }
  260. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
  261. {
  262. FLEXNetworkTransactionDetailTableViewController *detailViewController = [[FLEXNetworkTransactionDetailTableViewController alloc] init];
  263. detailViewController.transaction = [self transactionAtIndexPath:indexPath inTableView:tableView];
  264. [self.navigationController pushViewController:detailViewController animated:YES];
  265. }
  266. - (FLEXNetworkTransaction *)transactionAtIndexPath:(NSIndexPath *)indexPath inTableView:(UITableView *)tableView
  267. {
  268. FLEXNetworkTransaction *transaction = nil;
  269. if (tableView == self.tableView) {
  270. transaction = [self.networkTransactions objectAtIndex:indexPath.row];
  271. } else if (tableView == self.searchController.searchResultsTableView) {
  272. transaction = [self.filteredNetworkTransactions objectAtIndex:indexPath.row];
  273. }
  274. return transaction;
  275. }
  276. #pragma mark - Search display delegate
  277. - (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
  278. {
  279. [self updateSearchResultsWithSearchString:searchString];
  280. // Reload done after the data is filtered asynchronously
  281. return NO;
  282. }
  283. - (void)updateSearchResultsWithSearchString:(NSString *)searchString
  284. {
  285. dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
  286. NSArray *filteredNetworkTransactions = [self.networkTransactions filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^BOOL(FLEXNetworkTransaction *transaction, NSDictionary *bindings) {
  287. return [[transaction.request.URL absoluteString] rangeOfString:searchString options:NSCaseInsensitiveSearch].length > 0;
  288. }]];
  289. dispatch_async(dispatch_get_main_queue(), ^{
  290. if ([self.searchDisplayController.searchBar.text isEqual:searchString]) {
  291. self.filteredNetworkTransactions = filteredNetworkTransactions;
  292. [self.searchDisplayController.searchResultsTableView reloadData];
  293. }
  294. });
  295. });
  296. }
  297. @end