FLEXNetworkHistoryTableViewController.m 14 KB

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