DetailViewController.swift 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  1. //
  2. // DetailViewController.swift
  3. //
  4. // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/)
  5. //
  6. // Permission is hereby granted, free of charge, to any person obtaining a copy
  7. // of this software and associated documentation files (the "Software"), to deal
  8. // in the Software without restriction, including without limitation the rights
  9. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. // copies of the Software, and to permit persons to whom the Software is
  11. // furnished to do so, subject to the following conditions:
  12. //
  13. // The above copyright notice and this permission notice shall be included in
  14. // all copies or substantial portions of the Software.
  15. //
  16. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  18. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  19. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  20. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  21. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  22. // THE SOFTWARE.
  23. //
  24. import Alamofire
  25. import UIKit
  26. class DetailViewController: UITableViewController {
  27. enum Sections: Int {
  28. case Headers, Body
  29. }
  30. var request: Alamofire.Request? {
  31. didSet {
  32. oldValue?.cancel()
  33. title = request?.description
  34. refreshControl?.endRefreshing()
  35. headers.removeAll()
  36. body = nil
  37. elapsedTime = nil
  38. }
  39. }
  40. var headers: [String: String] = [:]
  41. var body: String?
  42. var elapsedTime: NSTimeInterval?
  43. var segueIdentifier: String?
  44. static let numberFormatter: NSNumberFormatter = {
  45. let formatter = NSNumberFormatter()
  46. formatter.numberStyle = .DecimalStyle
  47. return formatter
  48. }()
  49. // MARK: View Lifecycle
  50. override func awakeFromNib() {
  51. super.awakeFromNib()
  52. refreshControl?.addTarget(self, action: #selector(DetailViewController.refresh), forControlEvents: .ValueChanged)
  53. }
  54. override func viewDidAppear(animated: Bool) {
  55. super.viewDidAppear(animated)
  56. refresh()
  57. }
  58. // MARK: IBActions
  59. @IBAction func refresh() {
  60. guard let request = request else {
  61. return
  62. }
  63. refreshControl?.beginRefreshing()
  64. let start = CACurrentMediaTime()
  65. request.responseString { response in
  66. let end = CACurrentMediaTime()
  67. self.elapsedTime = end - start
  68. if let response = response.response {
  69. for (field, value) in response.allHeaderFields {
  70. self.headers["\(field)"] = "\(value)"
  71. }
  72. }
  73. if let segueIdentifier = self.segueIdentifier {
  74. switch segueIdentifier {
  75. case "GET", "POST", "PUT", "DELETE":
  76. self.body = response.result.value
  77. case "DOWNLOAD":
  78. self.body = self.downloadedBodyString()
  79. default:
  80. break
  81. }
  82. }
  83. self.tableView.reloadData()
  84. self.refreshControl?.endRefreshing()
  85. }
  86. }
  87. private func downloadedBodyString() -> String {
  88. let fileManager = NSFileManager.defaultManager()
  89. let cachesDirectory = fileManager.URLsForDirectory(.CachesDirectory, inDomains: .UserDomainMask)[0]
  90. do {
  91. let contents = try fileManager.contentsOfDirectoryAtURL(
  92. cachesDirectory,
  93. includingPropertiesForKeys: nil,
  94. options: .SkipsHiddenFiles
  95. )
  96. if let
  97. fileURL = contents.first,
  98. data = NSData(contentsOfURL: fileURL)
  99. {
  100. let json = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions())
  101. let prettyData = try NSJSONSerialization.dataWithJSONObject(json, options: .PrettyPrinted)
  102. if let prettyString = NSString(data: prettyData, encoding: NSUTF8StringEncoding) as? String {
  103. try fileManager.removeItemAtURL(fileURL)
  104. return prettyString
  105. }
  106. }
  107. } catch {
  108. // No-op
  109. }
  110. return ""
  111. }
  112. }
  113. // MARK: - UITableViewDataSource
  114. extension DetailViewController {
  115. override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  116. switch Sections(rawValue: section)! {
  117. case .Headers:
  118. return headers.count
  119. case .Body:
  120. return body == nil ? 0 : 1
  121. }
  122. }
  123. override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
  124. switch Sections(rawValue: indexPath.section)! {
  125. case .Headers:
  126. let cell = tableView.dequeueReusableCellWithIdentifier("Header")!
  127. let field = headers.keys.sort(<)[indexPath.row]
  128. let value = headers[field]
  129. cell.textLabel?.text = field
  130. cell.detailTextLabel?.text = value
  131. return cell
  132. case .Body:
  133. let cell = tableView.dequeueReusableCellWithIdentifier("Body")!
  134. cell.textLabel?.text = body
  135. return cell
  136. }
  137. }
  138. }
  139. // MARK: - UITableViewDelegate
  140. extension DetailViewController {
  141. override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
  142. return 2
  143. }
  144. override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
  145. if self.tableView(tableView, numberOfRowsInSection: section) == 0 {
  146. return ""
  147. }
  148. switch Sections(rawValue: section)! {
  149. case .Headers:
  150. return "Headers"
  151. case .Body:
  152. return "Body"
  153. }
  154. }
  155. override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
  156. switch Sections(rawValue: indexPath.section)! {
  157. case .Body:
  158. return 300
  159. default:
  160. return tableView.rowHeight
  161. }
  162. }
  163. override func tableView(tableView: UITableView, titleForFooterInSection section: Int) -> String? {
  164. if Sections(rawValue: section) == .Body, let elapsedTime = elapsedTime {
  165. let elapsedTimeText = DetailViewController.numberFormatter.stringFromNumber(elapsedTime) ?? "???"
  166. return "Elapsed Time: \(elapsedTimeText) sec"
  167. }
  168. return ""
  169. }
  170. }