DetailViewController.swift 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  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. self.title = self.request?.description
  32. self.refreshControl?.endRefreshing()
  33. self.headers.removeAll()
  34. self.body = nil
  35. self.elapsedTime = nil
  36. }
  37. }
  38. var headers: [String: String] = [:]
  39. var body: String?
  40. var elapsedTime: NSTimeInterval?
  41. var segueIdentifier: String?
  42. // MARK: View Lifecycle
  43. override func awakeFromNib() {
  44. super.awakeFromNib()
  45. self.refreshControl?.addTarget(self, action: "refresh", forControlEvents: .ValueChanged)
  46. }
  47. override func viewDidAppear(animated: Bool) {
  48. super.viewDidAppear(animated)
  49. self.refresh()
  50. }
  51. // MARK: IBActions
  52. @IBAction func refresh() {
  53. if self.request == nil {
  54. return
  55. }
  56. self.refreshControl?.beginRefreshing()
  57. let start = CACurrentMediaTime()
  58. self.request?.responseString { request, response, body, error in
  59. let end = CACurrentMediaTime()
  60. self.elapsedTime = end - start
  61. for (field, value) in response!.allHeaderFields {
  62. self.headers["\(field)"] = "\(value)"
  63. }
  64. if let segueIdentifier = self.segueIdentifier {
  65. switch segueIdentifier {
  66. case "GET", "POST", "PUT", "DELETE":
  67. self.body = body
  68. case "DOWNLOAD":
  69. self.body = self.downloadedBodyString()
  70. default:
  71. break
  72. }
  73. }
  74. self.tableView.reloadData()
  75. self.refreshControl?.endRefreshing()
  76. }
  77. }
  78. private func downloadedBodyString() -> String {
  79. let fileManager = NSFileManager.defaultManager()
  80. let cachesDirectory = fileManager.URLsForDirectory(.CachesDirectory, inDomains: .UserDomainMask)[0] as! NSURL
  81. if let
  82. contents = fileManager.contentsOfDirectoryAtURL(
  83. cachesDirectory,
  84. includingPropertiesForKeys: nil,
  85. options: .SkipsHiddenFiles,
  86. error: nil
  87. ),
  88. fileURL = contents.first as? NSURL,
  89. data = NSData(contentsOfURL: fileURL),
  90. json: AnyObject = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: nil),
  91. prettyData = NSJSONSerialization.dataWithJSONObject(json, options: .PrettyPrinted, error: nil),
  92. prettyString = NSString(data: prettyData, encoding: NSUTF8StringEncoding) as? String
  93. {
  94. fileManager.removeItemAtURL(fileURL, error: nil)
  95. return prettyString
  96. }
  97. return ""
  98. }
  99. }
  100. // MARK: - UITableViewDataSource
  101. extension DetailViewController: UITableViewDataSource {
  102. override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
  103. switch Sections(rawValue: section)! {
  104. case .Headers:
  105. return self.headers.count
  106. case .Body:
  107. return self.body == nil ? 0 : 1
  108. default:
  109. return 0
  110. }
  111. }
  112. override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
  113. switch Sections(rawValue: indexPath.section)! {
  114. case .Headers:
  115. let cell = self.tableView.dequeueReusableCellWithIdentifier("Header") as! UITableViewCell
  116. let field = self.headers.keys.array.sorted(<)[indexPath.row]
  117. let value = self.headers[field]
  118. cell.textLabel?.text = field
  119. cell.detailTextLabel!.text = value
  120. return cell
  121. case .Body:
  122. let cell = self.tableView.dequeueReusableCellWithIdentifier("Body") as! UITableViewCell
  123. cell.textLabel?.text = self.body
  124. return cell
  125. }
  126. }
  127. }
  128. // MARK: - UITableViewDelegate
  129. extension DetailViewController: UITableViewDelegate {
  130. override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
  131. return 2
  132. }
  133. override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
  134. if self.tableView(tableView, numberOfRowsInSection: section) == 0 {
  135. return ""
  136. }
  137. switch Sections(rawValue: section)! {
  138. case .Headers:
  139. return "Headers"
  140. case .Body:
  141. return "Body"
  142. }
  143. }
  144. override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
  145. switch Sections(rawValue: indexPath.section)! {
  146. case .Body:
  147. return 300
  148. default:
  149. return tableView.rowHeight
  150. }
  151. }
  152. override func tableView(tableView: UITableView, titleForFooterInSection section: Int) -> String? {
  153. if Sections(rawValue: section) == .Body, let elapsedTime = self.elapsedTime {
  154. let numberFormatter = NSNumberFormatter()
  155. numberFormatter.numberStyle = .DecimalStyle
  156. return "Elapsed Time: \(numberFormatter.stringFromNumber(elapsedTime)) sec"
  157. }
  158. return ""
  159. }
  160. }