StorageViewController.swift 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  1. // Copyright 2017 Google
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. import UIKit
  15. import FirebaseStorage
  16. class StorageViewController: UIViewController {
  17. /// An enum describing the different states of the view controller.
  18. private enum UIState: Equatable {
  19. /// No image is being shown, waiting on user action.
  20. case cleared
  21. /// Currently downloading from Firebase.
  22. case downloading(StorageTask)
  23. /// The image has downloaded and should be displayed.
  24. case downloaded(UIImage)
  25. /// Show an error message and stop downloading.
  26. case failed(String)
  27. /// Equatable support for UIState.
  28. static func == (lhs: StorageViewController.UIState,
  29. rhs: StorageViewController.UIState) -> Bool {
  30. switch (lhs, rhs) {
  31. case (.cleared, .cleared): return true
  32. case (.downloading, .downloading): return true
  33. case (.downloaded, .downloaded): return true
  34. case (.failed, .failed): return true
  35. default: return false
  36. }
  37. }
  38. }
  39. // MARK: - Properties
  40. /// The current internal state of the view controller.
  41. private var state: UIState = .cleared {
  42. didSet { changeState(from: oldValue, to: state) }
  43. }
  44. // MARK: Interface
  45. /// Image view to display the downloaded image.
  46. @IBOutlet var imageView: UIImageView!
  47. /// The download button.
  48. @IBOutlet var downloadButton: UIButton!
  49. /// The clear button.
  50. @IBOutlet var clearButton: UIButton!
  51. /// A visual representation of the state.
  52. @IBOutlet var stateLabel: UILabel!
  53. // MARK: - User Actions
  54. @IBAction func downloadButtonHit(_ sender: UIButton) {
  55. guard case .cleared = state else { return }
  56. // Start the download.
  57. let storage = Storage.storage()
  58. let ref = storage.reference(withPath: Constants.downloadPath)
  59. // TODO: Show progress bar here using proper API.
  60. let task = ref.getData(maxSize: Constants.maxSize) { [unowned self] data, error in
  61. guard let data = data else {
  62. self.state = .failed("Error downloading: \(error!.localizedDescription)")
  63. return
  64. }
  65. // Create a UIImage from the PNG data.
  66. guard let image = UIImage(data: data) else {
  67. self.state = .failed("Unable to initialize image with data downloaded.")
  68. return
  69. }
  70. self.state = .downloaded(image)
  71. }
  72. // The completion block above could be run before this line in some situations. If that's the
  73. // case, we don't need to do anything else and can return.
  74. if case .downloaded = state { return }
  75. // Set the state to downloading!
  76. state = .downloading(task)
  77. }
  78. @IBAction func clearButtonHit(_ sender: UIButton) {
  79. guard case .downloaded = state else { return }
  80. state = .cleared
  81. }
  82. // MARK: - State Management
  83. /// Changing from old state to new state.
  84. private func changeState(from oldState: UIState, to newState: UIState) {
  85. if oldState == newState { return }
  86. switch (oldState, newState) {
  87. // Regular state, start downloading the image.
  88. case (.cleared, .downloading(_)):
  89. // TODO: Update the UI with a spinner? Progress update?
  90. stateLabel.text = "State: Downloading..."
  91. // Download complete, ensure the download button is still off and enable the clear button.
  92. case let (_, .downloaded(image)):
  93. imageView.image = image
  94. stateLabel.text = "State: Image downloaded!"
  95. // Clear everything and reset to the original state.
  96. case (_, .cleared):
  97. imageView.image = nil
  98. stateLabel.text = "State: Pending download"
  99. // An error occurred.
  100. case let (_, .failed(error)):
  101. stateLabel.text = "State: \(error)"
  102. // For now, as the default, throw a fatal error because it's an unexpected state. This will
  103. // allow us to catch it immediately and add the required action or fix the bug.
  104. default:
  105. fatalError("Programmer error! Tried to go from \(oldState) to \(newState)")
  106. }
  107. }
  108. // MARK: - Constants
  109. /// Internal constants for this class.
  110. private enum Constants {
  111. /// The image name to download. Can comment this out and replace it with the other below it as
  112. /// part of the demo. Ensure that Storage has an image uploaded to this path for this to
  113. /// function properly.
  114. static let downloadPath = "YOUR_IMAGE_NAME.jpg"
  115. static let maxSize: Int64 = 1024 * 1024 * 10 // ~10MB
  116. }
  117. }