DetailViewController.swift 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  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.urlsForDirectory(.cachesDirectory, inDomains: .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,
  97. let data = try? Data(contentsOf: fileURL)
  98. {
  99. let json = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions())
  100. let prettyData = try JSONSerialization.data(withJSONObject: json, options: .prettyPrinted)
  101. if let prettyString = NSString(data: prettyData, encoding: String.Encoding.utf8.rawValue) as? String {
  102. try fileManager.removeItem(at: fileURL)
  103. return prettyString
  104. }
  105. }
  106. } catch {
  107. // No-op
  108. }
  109. return ""
  110. }
  111. }
  112. // MARK: - UITableViewDataSource
  113. extension DetailViewController {
  114. override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  115. switch Sections(rawValue: section)! {
  116. case .headers:
  117. return headers.count
  118. case .body:
  119. return body == nil ? 0 : 1
  120. }
  121. }
  122. override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
  123. switch Sections(rawValue: (indexPath as NSIndexPath).section)! {
  124. case .headers:
  125. let cell = tableView.dequeueReusableCell(withIdentifier: "Header")!
  126. let field = headers.keys.sorted(isOrderedBefore: <)[(indexPath as NSIndexPath).row]
  127. let value = headers[field]
  128. cell.textLabel?.text = field
  129. cell.detailTextLabel?.text = value
  130. return cell
  131. case .body:
  132. let cell = tableView.dequeueReusableCell(withIdentifier: "Body")!
  133. cell.textLabel?.text = body
  134. return cell
  135. }
  136. }
  137. }
  138. // MARK: - UITableViewDelegate
  139. extension DetailViewController {
  140. override func numberOfSections(in tableView: UITableView) -> Int {
  141. return 2
  142. }
  143. override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
  144. if self.tableView(tableView, numberOfRowsInSection: section) == 0 {
  145. return ""
  146. }
  147. switch Sections(rawValue: section)! {
  148. case .headers:
  149. return "Headers"
  150. case .body:
  151. return "Body"
  152. }
  153. }
  154. override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
  155. switch Sections(rawValue: (indexPath as NSIndexPath).section)! {
  156. case .body:
  157. return 300
  158. default:
  159. return tableView.rowHeight
  160. }
  161. }
  162. override func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
  163. if Sections(rawValue: section) == .body, let elapsedTime = elapsedTime {
  164. let elapsedTimeText = DetailViewController.numberFormatter.string(from: elapsedTime) ?? "???"
  165. return "Elapsed Time: \(elapsedTimeText) sec"
  166. }
  167. return ""
  168. }
  169. }