DetailViewController.swift 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  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: TimeInterval?
  43. var segueIdentifier: String?
  44. static let numberFormatter: NumberFormatter = {
  45. let formatter = NumberFormatter()
  46. formatter.numberStyle = .decimal
  47. return formatter
  48. }()
  49. // MARK: View Lifecycle
  50. override func awakeFromNib() {
  51. super.awakeFromNib()
  52. refreshControl?.addTarget(self, action: #selector(DetailViewController.refresh), for: .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 = FileManager.default
  89. let cachesDirectory = fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0]
  90. do {
  91. let contents = try fileManager.contentsOfDirectory(
  92. at: cachesDirectory,
  93. includingPropertiesForKeys: nil,
  94. options: .skipsHiddenFiles
  95. )
  96. if let fileURL = contents.first, let data = try? Data(contentsOf: fileURL) {
  97. let json = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions())
  98. let prettyData = try JSONSerialization.data(withJSONObject: json, options: .prettyPrinted)
  99. if let prettyString = String(data: prettyData, encoding: String.Encoding.utf8) {
  100. try fileManager.removeItem(at: fileURL)
  101. return prettyString
  102. }
  103. }
  104. } catch {
  105. // No-op
  106. }
  107. return ""
  108. }
  109. }
  110. // MARK: - UITableViewDataSource
  111. extension DetailViewController {
  112. override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  113. switch Sections(rawValue: section)! {
  114. case .headers:
  115. return headers.count
  116. case .body:
  117. return body == nil ? 0 : 1
  118. }
  119. }
  120. override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  121. switch Sections(rawValue: (indexPath as NSIndexPath).section)! {
  122. case .headers:
  123. let cell = tableView.dequeueReusableCell(withIdentifier: "Header")!
  124. let field = headers.keys.sorted(by: <)[indexPath.row]
  125. let value = headers[field]
  126. cell.textLabel?.text = field
  127. cell.detailTextLabel?.text = value
  128. return cell
  129. case .body:
  130. let cell = tableView.dequeueReusableCell(withIdentifier: "Body")!
  131. cell.textLabel?.text = body
  132. return cell
  133. }
  134. }
  135. }
  136. // MARK: - UITableViewDelegate
  137. extension DetailViewController {
  138. override func numberOfSections(in tableView: UITableView) -> Int {
  139. return 2
  140. }
  141. override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
  142. if self.tableView(tableView, numberOfRowsInSection: section) == 0 {
  143. return ""
  144. }
  145. switch Sections(rawValue: section)! {
  146. case .headers:
  147. return "Headers"
  148. case .body:
  149. return "Body"
  150. }
  151. }
  152. override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
  153. switch Sections(rawValue: (indexPath as NSIndexPath).section)! {
  154. case .body:
  155. return 300
  156. default:
  157. return tableView.rowHeight
  158. }
  159. }
  160. override func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
  161. if Sections(rawValue: section) == .body, let elapsedTime = elapsedTime {
  162. let elapsedTimeText = DetailViewController.numberFormatter.string(from: elapsedTime) ?? "???"
  163. return "Elapsed Time: \(elapsedTimeText) sec"
  164. }
  165. return ""
  166. }
  167. }