StorageViewController.swift 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  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, rhs: StorageViewController.UIState) -> Bool {
  29. switch (lhs, rhs) {
  30. case (.cleared, .cleared): return true
  31. case (.downloading, .downloading): return true
  32. case (.downloaded, .downloaded): return true
  33. case (.failed, .failed): return true
  34. default: return false
  35. }
  36. }
  37. }
  38. // MARK: - Properties
  39. /// The current internal state of the view controller.
  40. private var state: UIState = .cleared {
  41. didSet { changeState(from: oldValue, to: state) }
  42. }
  43. // MARK: Interface
  44. /// Image view to display the downloaded image.
  45. @IBOutlet var imageView: UIImageView!
  46. /// The download button.
  47. @IBOutlet var downloadButton: UIButton!
  48. /// The clear button.
  49. @IBOutlet var clearButton: UIButton!
  50. /// A visual representation of the state.
  51. @IBOutlet var stateLabel: UILabel!
  52. // MARK: - User Actions
  53. @IBAction func downloadButtonHit(_ sender: UIButton) {
  54. guard case .cleared = state else { return }
  55. // Start the download.
  56. let storage = Storage.storage()
  57. let ref = storage.reference(withPath: Constants.downloadPath)
  58. // TODO: Show progress bar here using proper API.
  59. let task = ref.getData(maxSize: Constants.maxSize) { [unowned self] data, error in
  60. guard let data = data else {
  61. self.state = .failed("Error downloading: \(error!.localizedDescription)")
  62. return
  63. }
  64. // Create a UIImage from the PNG data.
  65. guard let image = UIImage(data: data) else {
  66. self.state = .failed("Unable to initialize image with data downloaded.")
  67. return
  68. }
  69. self.state = .downloaded(image)
  70. }
  71. // The completion block above could be run before this line in some situations. If that's the
  72. // case, we don't need to do anything else and can return.
  73. if case .downloaded = state { return }
  74. // Set the state to downloading!
  75. state = .downloading(task)
  76. }
  77. @IBAction func clearButtonHit(_ sender: UIButton) {
  78. guard case .downloaded = state else { return }
  79. state = .cleared
  80. }
  81. // MARK: - State Management
  82. /// Changing from old state to new state.
  83. private func changeState(from oldState: UIState, to newState: UIState) {
  84. if oldState == newState { return }
  85. switch (oldState, newState) {
  86. // Regular state, start downloading the image.
  87. case (.cleared, .downloading(_)):
  88. // TODO: Update the UI with a spinner? Progress update?
  89. stateLabel.text = "State: Downloading..."
  90. // Download complete, ensure the download button is still off and enable the clear button.
  91. case let (_, .downloaded(image)):
  92. imageView.image = image
  93. stateLabel.text = "State: Image downloaded!"
  94. // Clear everything and reset to the original state.
  95. case (_, .cleared):
  96. imageView.image = nil
  97. stateLabel.text = "State: Pending download"
  98. // An error occurred.
  99. case let (_, .failed(error)):
  100. stateLabel.text = "State: \(error)"
  101. // For now, as the default, throw a fatal error because it's an unexpected state. This will
  102. // allow us to catch it immediately and add the required action or fix the bug.
  103. default:
  104. fatalError("Programmer error! Tried to go from \(oldState) to \(newState)")
  105. }
  106. }
  107. // MARK: - Constants
  108. /// Internal constants for this class.
  109. private struct Constants {
  110. /// The image name to download. Can comment this out and replace it with the other below it as
  111. /// part of the demo. Ensure that Storage has an image uploaded to this path for this to
  112. /// function properly.
  113. static let downloadPath = "YOUR_IMAGE_NAME.jpg"
  114. static let maxSize: Int64 = 1024 * 1024 * 10 // ~10MB
  115. }
  116. }