FLEXNetworkTransactionDetailTableViewController.m 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  1. //
  2. // FLEXNetworkTransactionDetailTableViewController.m
  3. // Flipboard
  4. //
  5. // Created by Ryan Olson on 2/10/15.
  6. // Copyright (c) 2015 Flipboard. All rights reserved.
  7. //
  8. #import "FLEXColor.h"
  9. #import "FLEXNetworkTransactionDetailTableViewController.h"
  10. #import "FLEXNetworkCurlLogger.h"
  11. #import "FLEXNetworkRecorder.h"
  12. #import "FLEXNetworkTransaction.h"
  13. #import "FLEXWebViewController.h"
  14. #import "FLEXImagePreviewViewController.h"
  15. #import "FLEXMultilineTableViewCell.h"
  16. #import "FLEXUtility.h"
  17. #import "FLEXManager+Private.h"
  18. #import "FLEXTableView.h"
  19. typedef UIViewController *(^FLEXNetworkDetailRowSelectionFuture)(void);
  20. @interface FLEXNetworkDetailRow : NSObject
  21. @property (nonatomic, copy) NSString *title;
  22. @property (nonatomic, copy) NSString *detailText;
  23. @property (nonatomic, copy) FLEXNetworkDetailRowSelectionFuture selectionFuture;
  24. @end
  25. @implementation FLEXNetworkDetailRow
  26. @end
  27. @interface FLEXNetworkDetailSection : NSObject
  28. @property (nonatomic, copy) NSString *title;
  29. @property (nonatomic, copy) NSArray<FLEXNetworkDetailRow *> *rows;
  30. @end
  31. @implementation FLEXNetworkDetailSection
  32. @end
  33. @interface FLEXNetworkTransactionDetailTableViewController ()
  34. @property (nonatomic, copy) NSArray<FLEXNetworkDetailSection *> *sections;
  35. @end
  36. @implementation FLEXNetworkTransactionDetailTableViewController
  37. - (instancetype)initWithStyle:(UITableViewStyle)style
  38. {
  39. // Force grouped style
  40. self = [super initWithStyle:UITableViewStyleGrouped];
  41. if (self) {
  42. [NSNotificationCenter.defaultCenter addObserver:self selector:@selector(handleTransactionUpdatedNotification:) name:kFLEXNetworkRecorderTransactionUpdatedNotification object:nil];
  43. self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Copy curl" style:UIBarButtonItemStylePlain target:self action:@selector(copyButtonPressed:)];
  44. }
  45. return self;
  46. }
  47. - (void)viewDidLoad
  48. {
  49. [super viewDidLoad];
  50. [self.tableView registerClass:[FLEXMultilineTableViewCell class] forCellReuseIdentifier:kFLEXMultilineCell];
  51. }
  52. - (void)setTransaction:(FLEXNetworkTransaction *)transaction
  53. {
  54. if (![_transaction isEqual:transaction]) {
  55. _transaction = transaction;
  56. self.title = [transaction.request.URL lastPathComponent];
  57. [self rebuildTableSections];
  58. }
  59. }
  60. - (void)setSections:(NSArray<FLEXNetworkDetailSection *> *)sections
  61. {
  62. if (![_sections isEqual:sections]) {
  63. _sections = [sections copy];
  64. [self.tableView reloadData];
  65. }
  66. }
  67. - (void)rebuildTableSections
  68. {
  69. NSMutableArray<FLEXNetworkDetailSection *> *sections = [NSMutableArray array];
  70. FLEXNetworkDetailSection *generalSection = [[self class] generalSectionForTransaction:self.transaction];
  71. if (generalSection.rows.count > 0) {
  72. [sections addObject:generalSection];
  73. }
  74. FLEXNetworkDetailSection *requestHeadersSection = [[self class] requestHeadersSectionForTransaction:self.transaction];
  75. if (requestHeadersSection.rows.count > 0) {
  76. [sections addObject:requestHeadersSection];
  77. }
  78. FLEXNetworkDetailSection *queryParametersSection = [[self class] queryParametersSectionForTransaction:self.transaction];
  79. if (queryParametersSection.rows.count > 0) {
  80. [sections addObject:queryParametersSection];
  81. }
  82. FLEXNetworkDetailSection *postBodySection = [[self class] postBodySectionForTransaction:self.transaction];
  83. if (postBodySection.rows.count > 0) {
  84. [sections addObject:postBodySection];
  85. }
  86. FLEXNetworkDetailSection *responseHeadersSection = [[self class] responseHeadersSectionForTransaction:self.transaction];
  87. if (responseHeadersSection.rows.count > 0) {
  88. [sections addObject:responseHeadersSection];
  89. }
  90. self.sections = sections;
  91. }
  92. - (void)handleTransactionUpdatedNotification:(NSNotification *)notification
  93. {
  94. FLEXNetworkTransaction *transaction = [[notification userInfo] objectForKey:kFLEXNetworkRecorderUserInfoTransactionKey];
  95. if (transaction == self.transaction) {
  96. [self rebuildTableSections];
  97. }
  98. }
  99. - (void)copyButtonPressed:(id)sender
  100. {
  101. [UIPasteboard.generalPasteboard setString:[FLEXNetworkCurlLogger curlCommandString:_transaction.request]];
  102. }
  103. #pragma mark - Table view data source
  104. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
  105. {
  106. return self.sections.count;
  107. }
  108. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
  109. {
  110. FLEXNetworkDetailSection *sectionModel = self.sections[section];
  111. return sectionModel.rows.count;
  112. }
  113. - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
  114. {
  115. FLEXNetworkDetailSection *sectionModel = self.sections[section];
  116. return sectionModel.title;
  117. }
  118. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
  119. {
  120. FLEXMultilineTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kFLEXMultilineCell forIndexPath:indexPath];
  121. FLEXNetworkDetailRow *rowModel = [self rowModelAtIndexPath:indexPath];
  122. cell.textLabel.attributedText = [[self class] attributedTextForRow:rowModel];
  123. cell.accessoryType = rowModel.selectionFuture ? UITableViewCellAccessoryDisclosureIndicator : UITableViewCellAccessoryNone;
  124. cell.selectionStyle = rowModel.selectionFuture ? UITableViewCellSelectionStyleDefault : UITableViewCellSelectionStyleNone;
  125. return cell;
  126. }
  127. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
  128. {
  129. FLEXNetworkDetailRow *rowModel = [self rowModelAtIndexPath:indexPath];
  130. UIViewController *viewController = nil;
  131. if (rowModel.selectionFuture) {
  132. viewController = rowModel.selectionFuture();
  133. }
  134. if ([viewController isKindOfClass:UIAlertController.class]) {
  135. [self presentViewController:viewController animated:YES completion:nil];
  136. } else if (viewController) {
  137. [self.navigationController pushViewController:viewController animated:YES];
  138. }
  139. [tableView deselectRowAtIndexPath:indexPath animated:YES];
  140. }
  141. - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
  142. {
  143. FLEXNetworkDetailRow *row = [self rowModelAtIndexPath:indexPath];
  144. NSAttributedString *attributedText = [[self class] attributedTextForRow:row];
  145. BOOL showsAccessory = row.selectionFuture != nil;
  146. return [FLEXMultilineTableViewCell
  147. preferredHeightWithAttributedText:attributedText
  148. maxWidth:tableView.bounds.size.width
  149. style:tableView.style
  150. showsAccessory:showsAccessory
  151. ];
  152. }
  153. - (FLEXNetworkDetailRow *)rowModelAtIndexPath:(NSIndexPath *)indexPath
  154. {
  155. FLEXNetworkDetailSection *sectionModel = self.sections[indexPath.section];
  156. return sectionModel.rows[indexPath.row];
  157. }
  158. #pragma mark - Cell Copying
  159. - (BOOL)tableView:(UITableView *)tableView shouldShowMenuForRowAtIndexPath:(NSIndexPath *)indexPath
  160. {
  161. return YES;
  162. }
  163. - (BOOL)tableView:(UITableView *)tableView canPerformAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender
  164. {
  165. return action == @selector(copy:);
  166. }
  167. - (void)tableView:(UITableView *)tableView performAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender
  168. {
  169. if (action == @selector(copy:)) {
  170. FLEXNetworkDetailRow *row = [self rowModelAtIndexPath:indexPath];
  171. UIPasteboard.generalPasteboard.string = row.detailText;
  172. }
  173. }
  174. #if FLEX_AT_LEAST_IOS13_SDK
  175. - (UIContextMenuConfiguration *)tableView:(UITableView *)tableView contextMenuConfigurationForRowAtIndexPath:(NSIndexPath *)indexPath point:(CGPoint)point __IOS_AVAILABLE(13.0)
  176. {
  177. return [UIContextMenuConfiguration
  178. configurationWithIdentifier:nil
  179. previewProvider:nil
  180. actionProvider:^UIMenu *(NSArray<UIMenuElement *> *suggestedActions) {
  181. UIAction *copy = [UIAction
  182. actionWithTitle:@"Copy"
  183. image:nil
  184. identifier:nil
  185. handler:^(__kindof UIAction *action) {
  186. FLEXNetworkDetailRow *row = [self rowModelAtIndexPath:indexPath];
  187. UIPasteboard.generalPasteboard.string = row.detailText;
  188. }
  189. ];
  190. return [UIMenu
  191. menuWithTitle:@"" image:nil identifier:nil
  192. options:UIMenuOptionsDisplayInline
  193. children:@[copy]
  194. ];
  195. }
  196. ];
  197. }
  198. #endif
  199. #pragma mark - View Configuration
  200. + (NSAttributedString *)attributedTextForRow:(FLEXNetworkDetailRow *)row
  201. {
  202. NSDictionary<NSString *, id> *titleAttributes = @{ NSFontAttributeName : [UIFont fontWithName:@"HelveticaNeue-Medium" size:12.0],
  203. NSForegroundColorAttributeName : [UIColor colorWithWhite:0.5 alpha:1.0] };
  204. NSDictionary<NSString *, id> *detailAttributes = @{ NSFontAttributeName : UIFont.flex_defaultTableCellFont,
  205. NSForegroundColorAttributeName : [FLEXColor primaryTextColor] };
  206. NSString *title = [NSString stringWithFormat:@"%@: ", row.title];
  207. NSString *detailText = row.detailText ?: @"";
  208. NSMutableAttributedString *attributedText = [NSMutableAttributedString new];
  209. [attributedText appendAttributedString:[[NSAttributedString alloc] initWithString:title attributes:titleAttributes]];
  210. [attributedText appendAttributedString:[[NSAttributedString alloc] initWithString:detailText attributes:detailAttributes]];
  211. return attributedText;
  212. }
  213. #pragma mark - Table Data Generation
  214. + (FLEXNetworkDetailSection *)generalSectionForTransaction:(FLEXNetworkTransaction *)transaction
  215. {
  216. NSMutableArray<FLEXNetworkDetailRow *> *rows = [NSMutableArray array];
  217. FLEXNetworkDetailRow *requestURLRow = [FLEXNetworkDetailRow new];
  218. requestURLRow.title = @"Request URL";
  219. NSURL *url = transaction.request.URL;
  220. requestURLRow.detailText = url.absoluteString;
  221. requestURLRow.selectionFuture = ^{
  222. UIViewController *urlWebViewController = [[FLEXWebViewController alloc] initWithURL:url];
  223. urlWebViewController.title = url.absoluteString;
  224. return urlWebViewController;
  225. };
  226. [rows addObject:requestURLRow];
  227. FLEXNetworkDetailRow *requestMethodRow = [FLEXNetworkDetailRow new];
  228. requestMethodRow.title = @"Request Method";
  229. requestMethodRow.detailText = transaction.request.HTTPMethod;
  230. [rows addObject:requestMethodRow];
  231. if (transaction.cachedRequestBody.length > 0) {
  232. FLEXNetworkDetailRow *postBodySizeRow = [FLEXNetworkDetailRow new];
  233. postBodySizeRow.title = @"Request Body Size";
  234. postBodySizeRow.detailText = [NSByteCountFormatter stringFromByteCount:transaction.cachedRequestBody.length countStyle:NSByteCountFormatterCountStyleBinary];
  235. [rows addObject:postBodySizeRow];
  236. FLEXNetworkDetailRow *postBodyRow = [FLEXNetworkDetailRow new];
  237. postBodyRow.title = @"Request Body";
  238. postBodyRow.detailText = @"tap to view";
  239. postBodyRow.selectionFuture = ^UIViewController * () {
  240. // Show the body if we can
  241. NSString *contentType = [transaction.request valueForHTTPHeaderField:@"Content-Type"];
  242. UIViewController *detailViewController = [self detailViewControllerForMIMEType:contentType data:[self postBodyDataForTransaction:transaction]];
  243. if (detailViewController) {
  244. detailViewController.title = @"Request Body";
  245. return detailViewController;
  246. }
  247. // We can't show the body, alert user
  248. return [FLEXAlert makeAlert:^(FLEXAlert *make) {
  249. make.title(@"Can't View HTTP Body Data");
  250. make.message(@"FLEX does not have a viewer for request body data with MIME type: ");
  251. make.message(contentType);
  252. make.button(@"Dismiss").cancelStyle();
  253. }];
  254. };
  255. [rows addObject:postBodyRow];
  256. }
  257. NSString *statusCodeString = [FLEXUtility statusCodeStringFromURLResponse:transaction.response];
  258. if (statusCodeString.length > 0) {
  259. FLEXNetworkDetailRow *statusCodeRow = [FLEXNetworkDetailRow new];
  260. statusCodeRow.title = @"Status Code";
  261. statusCodeRow.detailText = statusCodeString;
  262. [rows addObject:statusCodeRow];
  263. }
  264. if (transaction.error) {
  265. FLEXNetworkDetailRow *errorRow = [FLEXNetworkDetailRow new];
  266. errorRow.title = @"Error";
  267. errorRow.detailText = transaction.error.localizedDescription;
  268. [rows addObject:errorRow];
  269. }
  270. FLEXNetworkDetailRow *responseBodyRow = [FLEXNetworkDetailRow new];
  271. responseBodyRow.title = @"Response Body";
  272. NSData *responseData = [[FLEXNetworkRecorder defaultRecorder] cachedResponseBodyForTransaction:transaction];
  273. if (responseData.length > 0) {
  274. responseBodyRow.detailText = @"tap to view";
  275. // Avoid a long lived strong reference to the response data in case we need to purge it from the cache.
  276. __weak NSData *weakResponseData = responseData;
  277. responseBodyRow.selectionFuture = ^UIViewController * () {
  278. // Show the response if we can
  279. NSString *contentType = transaction.response.MIMEType;
  280. NSData *strongResponseData = weakResponseData;
  281. if (strongResponseData) {
  282. UIViewController *bodyDetailController = [self detailViewControllerForMIMEType:contentType data:strongResponseData];
  283. if (bodyDetailController) {
  284. bodyDetailController.title = @"Response";
  285. return bodyDetailController;
  286. }
  287. }
  288. // We can't show the response, alert user
  289. return [FLEXAlert makeAlert:^(FLEXAlert *make) {
  290. make.title(@"Unable to View Response");
  291. if (strongResponseData) {
  292. make.message(@"No viewer content type: ").message(contentType);
  293. } else {
  294. make.message(@"The response has been purged from the cache");
  295. }
  296. make.button(@"OK").cancelStyle();
  297. }];
  298. };
  299. } else {
  300. BOOL emptyResponse = transaction.receivedDataLength == 0;
  301. responseBodyRow.detailText = emptyResponse ? @"empty" : @"not in cache";
  302. }
  303. [rows addObject:responseBodyRow];
  304. FLEXNetworkDetailRow *responseSizeRow = [FLEXNetworkDetailRow new];
  305. responseSizeRow.title = @"Response Size";
  306. responseSizeRow.detailText = [NSByteCountFormatter stringFromByteCount:transaction.receivedDataLength countStyle:NSByteCountFormatterCountStyleBinary];
  307. [rows addObject:responseSizeRow];
  308. FLEXNetworkDetailRow *mimeTypeRow = [FLEXNetworkDetailRow new];
  309. mimeTypeRow.title = @"MIME Type";
  310. mimeTypeRow.detailText = transaction.response.MIMEType;
  311. [rows addObject:mimeTypeRow];
  312. FLEXNetworkDetailRow *mechanismRow = [FLEXNetworkDetailRow new];
  313. mechanismRow.title = @"Mechanism";
  314. mechanismRow.detailText = transaction.requestMechanism;
  315. [rows addObject:mechanismRow];
  316. NSDateFormatter *startTimeFormatter = [NSDateFormatter new];
  317. startTimeFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss.SSS";
  318. FLEXNetworkDetailRow *localStartTimeRow = [FLEXNetworkDetailRow new];
  319. localStartTimeRow.title = [NSString stringWithFormat:@"Start Time (%@)", [[NSTimeZone localTimeZone] abbreviationForDate:transaction.startTime]];
  320. localStartTimeRow.detailText = [startTimeFormatter stringFromDate:transaction.startTime];
  321. [rows addObject:localStartTimeRow];
  322. startTimeFormatter.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"];
  323. FLEXNetworkDetailRow *utcStartTimeRow = [FLEXNetworkDetailRow new];
  324. utcStartTimeRow.title = @"Start Time (UTC)";
  325. utcStartTimeRow.detailText = [startTimeFormatter stringFromDate:transaction.startTime];
  326. [rows addObject:utcStartTimeRow];
  327. FLEXNetworkDetailRow *unixStartTime = [FLEXNetworkDetailRow new];
  328. unixStartTime.title = @"Unix Start Time";
  329. unixStartTime.detailText = [NSString stringWithFormat:@"%f", [transaction.startTime timeIntervalSince1970]];
  330. [rows addObject:unixStartTime];
  331. FLEXNetworkDetailRow *durationRow = [FLEXNetworkDetailRow new];
  332. durationRow.title = @"Total Duration";
  333. durationRow.detailText = [FLEXUtility stringFromRequestDuration:transaction.duration];
  334. [rows addObject:durationRow];
  335. FLEXNetworkDetailRow *latencyRow = [FLEXNetworkDetailRow new];
  336. latencyRow.title = @"Latency";
  337. latencyRow.detailText = [FLEXUtility stringFromRequestDuration:transaction.latency];
  338. [rows addObject:latencyRow];
  339. FLEXNetworkDetailSection *generalSection = [FLEXNetworkDetailSection new];
  340. generalSection.title = @"General";
  341. generalSection.rows = rows;
  342. return generalSection;
  343. }
  344. + (FLEXNetworkDetailSection *)requestHeadersSectionForTransaction:(FLEXNetworkTransaction *)transaction
  345. {
  346. FLEXNetworkDetailSection *requestHeadersSection = [FLEXNetworkDetailSection new];
  347. requestHeadersSection.title = @"Request Headers";
  348. requestHeadersSection.rows = [self networkDetailRowsFromDictionary:transaction.request.allHTTPHeaderFields];
  349. return requestHeadersSection;
  350. }
  351. + (FLEXNetworkDetailSection *)postBodySectionForTransaction:(FLEXNetworkTransaction *)transaction
  352. {
  353. FLEXNetworkDetailSection *postBodySection = [FLEXNetworkDetailSection new];
  354. postBodySection.title = @"Request Body Parameters";
  355. if (transaction.cachedRequestBody.length > 0) {
  356. NSString *contentType = [transaction.request valueForHTTPHeaderField:@"Content-Type"];
  357. if ([contentType hasPrefix:@"application/x-www-form-urlencoded"]) {
  358. NSString *bodyString = [NSString stringWithCString:[self postBodyDataForTransaction:transaction].bytes encoding:NSUTF8StringEncoding];
  359. postBodySection.rows = [self networkDetailRowsFromQueryItems:[FLEXUtility itemsFromQueryString:bodyString]];
  360. }
  361. }
  362. return postBodySection;
  363. }
  364. + (FLEXNetworkDetailSection *)queryParametersSectionForTransaction:(FLEXNetworkTransaction *)transaction
  365. {
  366. NSArray<NSURLQueryItem *> *queries = [FLEXUtility itemsFromQueryString:transaction.request.URL.query];
  367. FLEXNetworkDetailSection *querySection = [FLEXNetworkDetailSection new];
  368. querySection.title = @"Query Parameters";
  369. querySection.rows = [self networkDetailRowsFromQueryItems:queries];
  370. return querySection;
  371. }
  372. + (FLEXNetworkDetailSection *)responseHeadersSectionForTransaction:(FLEXNetworkTransaction *)transaction
  373. {
  374. FLEXNetworkDetailSection *responseHeadersSection = [FLEXNetworkDetailSection new];
  375. responseHeadersSection.title = @"Response Headers";
  376. if ([transaction.response isKindOfClass:[NSHTTPURLResponse class]]) {
  377. NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)transaction.response;
  378. responseHeadersSection.rows = [self networkDetailRowsFromDictionary:httpResponse.allHeaderFields];
  379. }
  380. return responseHeadersSection;
  381. }
  382. + (NSArray<FLEXNetworkDetailRow *> *)networkDetailRowsFromDictionary:(NSDictionary<NSString *, id> *)dictionary
  383. {
  384. NSMutableArray<FLEXNetworkDetailRow *> *rows = [NSMutableArray new];
  385. NSArray<NSString *> *sortedKeys = [dictionary.allKeys sortedArrayUsingSelector:@selector(caseInsensitiveCompare:)];
  386. for (NSString *key in sortedKeys) {
  387. id value = dictionary[key];
  388. FLEXNetworkDetailRow *row = [FLEXNetworkDetailRow new];
  389. row.title = key;
  390. row.detailText = [value description];
  391. [rows addObject:row];
  392. }
  393. return rows.copy;
  394. }
  395. + (NSArray<FLEXNetworkDetailRow *> *)networkDetailRowsFromQueryItems:(NSArray<NSURLQueryItem *> *)items
  396. {
  397. // Sort the items by name
  398. items = [items sortedArrayUsingComparator:^NSComparisonResult(NSURLQueryItem *item1, NSURLQueryItem *item2) {
  399. return [item1.name caseInsensitiveCompare:item2.name];
  400. }];
  401. NSMutableArray<FLEXNetworkDetailRow *> *rows = [NSMutableArray new];
  402. for (NSURLQueryItem *item in items) {
  403. FLEXNetworkDetailRow *row = [FLEXNetworkDetailRow new];
  404. row.title = item.name;
  405. row.detailText = item.value;
  406. [rows addObject:row];
  407. }
  408. return [rows copy];
  409. }
  410. + (UIViewController *)detailViewControllerForMIMEType:(NSString *)mimeType data:(NSData *)data
  411. {
  412. FLEXCustomContentViewerFuture makeCustomViewer = [FLEXManager sharedManager].customContentTypeViewers[mimeType.lowercaseString];
  413. if (makeCustomViewer) {
  414. UIViewController *viewer = makeCustomViewer(data);
  415. if (viewer) {
  416. return viewer;
  417. }
  418. }
  419. // FIXME (RKO): Don't rely on UTF8 string encoding
  420. UIViewController *detailViewController = nil;
  421. if ([FLEXUtility isValidJSONData:data]) {
  422. NSString *prettyJSON = [FLEXUtility prettyJSONStringFromData:data];
  423. if (prettyJSON.length > 0) {
  424. detailViewController = [[FLEXWebViewController alloc] initWithText:prettyJSON];
  425. }
  426. } else if ([mimeType hasPrefix:@"image/"]) {
  427. UIImage *image = [UIImage imageWithData:data];
  428. detailViewController = [FLEXImagePreviewViewController forImage:image];
  429. } else if ([mimeType isEqual:@"application/x-plist"]) {
  430. id propertyList = [NSPropertyListSerialization propertyListWithData:data options:0 format:NULL error:NULL];
  431. detailViewController = [[FLEXWebViewController alloc] initWithText:[propertyList description]];
  432. }
  433. // Fall back to trying to show the response as text
  434. if (!detailViewController) {
  435. NSString *text = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
  436. if (text.length > 0) {
  437. detailViewController = [[FLEXWebViewController alloc] initWithText:text];
  438. }
  439. }
  440. return detailViewController;
  441. }
  442. + (NSData *)postBodyDataForTransaction:(FLEXNetworkTransaction *)transaction
  443. {
  444. NSData *bodyData = transaction.cachedRequestBody;
  445. if (bodyData.length > 0) {
  446. NSString *contentEncoding = [transaction.request valueForHTTPHeaderField:@"Content-Encoding"];
  447. if ([contentEncoding rangeOfString:@"deflate" options:NSCaseInsensitiveSearch].length > 0 || [contentEncoding rangeOfString:@"gzip" options:NSCaseInsensitiveSearch].length > 0) {
  448. bodyData = [FLEXUtility inflatedDataFromCompressedData:bodyData];
  449. }
  450. }
  451. return bodyData;
  452. }
  453. @end