DetailViewController.swift 6.4 KB

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