Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WIP Add SwiftUI Quickstart for Storage #1134

Draft
wants to merge 1 commit into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 19 additions & 5 deletions storage/Podfile
Original file line number Diff line number Diff line change
@@ -1,15 +1,29 @@
# StorageExample

use_frameworks!
platform :ios, '10.0'

pod 'Firebase/Analytics'
pod 'Firebase/Auth'
pod 'Firebase/Storage'

target 'StorageExample' do
platform :ios, '10.0'

pod 'Firebase/Analytics'
pod 'Firebase/Auth'
pod 'Firebase/Storage'
end
target 'StorageExampleSwift' do
platform :ios, '10.0'

pod 'Firebase/Analytics'
pod 'Firebase/Auth'
pod 'Firebase/Storage'
pod 'FirebaseStorageSwift', "~> 7.0-beta"
end
target 'StorageExampleSwiftUI' do
platform :ios, '13.0'

pod 'Firebase'
pod 'Firebase/Analytics'
pod 'Firebase/Auth'
pod 'Firebase/Storage'
pod 'FirebaseStorageSwift', "~> 7.0-beta"
end
target 'StorageExampleTests' do
Expand Down
5 changes: 4 additions & 1 deletion storage/Podfile.lock
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
PODS:
- Firebase (7.4.0):
- Firebase/Core (= 7.4.0)
- Firebase/Analytics (7.4.0):
- Firebase/Core
- Firebase/Auth (7.4.0):
Expand Down Expand Up @@ -81,6 +83,7 @@ PODS:
- PromisesObjC (1.2.12)

DEPENDENCIES:
- Firebase
- Firebase/Analytics
- Firebase/Auth
- Firebase/Storage
Expand Down Expand Up @@ -119,6 +122,6 @@ SPEC CHECKSUMS:
nanopb: 59221d7f958fb711001e6a449489542d92ae113e
PromisesObjC: 3113f7f76903778cf4a0586bd1ab89329a0b7b97

PODFILE CHECKSUM: 68e67a7f5b716247bf88b244cb2b3cc55d2e53ec
PODFILE CHECKSUM: 25b9e14f35ae5e264d830941bf9f0c8c3b02ce6b

COCOAPODS: 1.10.1
316 changes: 315 additions & 1 deletion storage/StorageExample.xcodeproj/project.pbxproj

Large diffs are not rendered by default.

100 changes: 100 additions & 0 deletions storage/StorageExampleSwiftUI/ImagePicker.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
// Copyright 2021 Google LLC
//
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I know this repo isn't consistent with this, but please use the standard Firebase open source copyright like https://github.com/firebase/firebase-ios-sdk/blob/master/FirebaseStorageSwift/Sources/SwiftAPIExtension.swift#L1

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

import SwiftUI
import Firebase

/// ImagePickerRepresentable wraps a UIImagePickerController, so it is accessible through SwiftUI.
struct ImagePickerRepresentable {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nice job with what you have going on this file. 👏 hopefully Apple provides us with a standard PhotoPicker view that saves us from having to do all of this 🤞

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you. Maybe there will be something announced in June. It really seems like SwiftUI was a second class citizen for the new photo APIs, so I expect them to fix that.

enum Source {
case camera
case photoLibrary
}

/// Denotes whether the user is taking a photo or selecting one.
var source: Source

/// Persistent storage which retains the image.
@ObservedObject var store: ImageStore

/// Binds to whether the image picker is visible.
@Binding var visible: Bool

/// Completion handler that is invoked when the image picker dismisses.
var completion: () -> Void

/// Coordinator is an internal class that acts as a delegate for the image picker.
class Coordinator: NSObject {
private var representable: ImagePickerRepresentable
private var store: ImageStore

init(representable: ImagePickerRepresentable, store: ImageStore) {
self.representable = representable
self.store = store
}
}
}

extension ImagePickerRepresentable: UIViewControllerRepresentable {
typealias UIViewControllerType = UIImagePickerController

/// Invoked by the system to setup a coordinator that the UIImagePickerViewController can use.
/// - Returns: The coordinator.
func makeCoordinator() -> Coordinator {
Coordinator(representable: self, store: self.store)
}

func makeUIViewController(context: Context) -> UIImagePickerController {
let imagePicker = UIImagePickerController()

switch self.source {
case .camera:
imagePicker.sourceType = .camera
imagePicker.cameraCaptureMode = .photo
case .photoLibrary:
imagePicker.sourceType = .photoLibrary
}

imagePicker.delegate = context.coordinator
return imagePicker
}

/// Required to implement, but unnecessary. We do not need to invalidate the SwiftUI canvas.
func updateUIViewController(_ uiViewController: UIImagePickerController, context: Context) { }
}

extension ImagePickerRepresentable.Coordinator: UIImagePickerControllerDelegate {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If you haven't considered it, check out PHPickerViewController as well. There's a cool WWDC 2020 video where I learned about it

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ive read a few cool articles about it. like this this one

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey @ncooke3, I really wanted to use it too haha. I started with the PHPickerViewController. I got it working but I found two issues:

  1. PHPickerViewController does not provide any access to the camera yet, so I was forced to also incorporate UIImagePickerController or get a camera manually.

  2. There is a bug I found when using search in the PHPickerViewController and SwiftUI on an actual device. On my iPhone 12 Pro Max, the picker view process crashes whenever using the search bar. The rest of the controller behaves as usual. I opened feedback with Apple to address it.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I didnt know that but that's good to know! 👍

func imagePickerController(
_ picker: UIImagePickerController,
didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]
) {
if let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
// TODO: Consider displaying a progress bar or spinner here
store.saveImage(image) { result in
// TODO: Handle the error
self.representable.visible = false
picker.dismiss(animated: true, completion: self.representable.completion)
}
}
}

func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
self.representable.visible = false
picker.dismiss(animated: true, completion: self.representable.completion)
}
}

/// The coordinator must implement the UINavigationControllerDelegate protocol in order to be the
/// UIImagePickerController's delegate.
extension ImagePickerRepresentable.Coordinator: UINavigationControllerDelegate { }
99 changes: 99 additions & 0 deletions storage/StorageExampleSwiftUI/ImageStore.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

import Firebase
import FirebaseStorageSwift

/// ImageStore facilitates saving and loading an image.
public class ImageStore: ObservableObject {
/// Reference to Firebase storage.
private var storage: Storage

/// Quality for JPEG images where 1.0 is the best quality and 0.0 is the worst.
public var compressionQuality: CGFloat = 0.8

/// UserDefaults key that will have a value containing the path of the last image.
public let imagePathKey = "imagePath"

/// Binds to the current image.
@Published var image: UIImage?

lazy var localImageFileDirectory: String = {
let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
let documentsDirectory = paths[0]
return "file:\(documentsDirectory)"
}()

public init(storage: Storage) {
self.storage = storage
}

/// Saves an image in the store.
/// - Parameter image: The image to save.
public func saveImage(_ image: UIImage, completion: @escaping (Result<Void, Error>) -> Void) {
self.image = image
let imagePath = "\(Auth.auth().currentUser!.uid)/\(Int(Date.timeIntervalSinceReferenceDate * 1000)).jpg"
uploadImage(image, atPath: imagePath) { result in
UserDefaults.standard.setValue(imagePath, forKey: self.imagePathKey)
completion(result)
}
}

/// Loads the most recent image.
public func loadImage() {
if let imagePath = UserDefaults.standard.string(forKey: imagePathKey) {
downloadImage(atPath: imagePath)
}
}

/// Uploads an image to Firebase storage.
/// - Parameters:
/// - image: Image to upload.
/// - imagePath: Path of the image in Firebase storage.
private func uploadImage(
_ image: UIImage,
atPath imagePath: String,
completion: @escaping (Result<Void, Error>) -> Void
) {
guard let imageData = image.jpegData(compressionQuality: compressionQuality) else { return }

let imageMetadata = StorageMetadata()
imageMetadata.contentType = "image/jpeg"

let storageRef = storage.reference(withPath: imagePath)
storageRef.putData(imageData, metadata: imageMetadata) { result in
switch result {
case .success:
completion(.success(()))
case let .failure(error):
completion(.failure(error))
break
}
}
}

/// Downloads an image from Firebase storage.
/// - Parameter imagePath: Path of the image in Firebase storage.
private func downloadImage(atPath imagePath: String) {
guard let imageURL = URL(string: "\(self.localImageFileDirectory)/\(imagePath)") else { return }
self.storage.reference().child(imagePath).write(toFile: imageURL) { result in
switch result {
case let .success(downloadedFileURL):
self.image = UIImage(contentsOfFile: downloadedFileURL.path)
case let .failure(error):
print("Error downloading: \(error)")
}
}
}
}
94 changes: 94 additions & 0 deletions storage/StorageExampleSwiftUI/ImageView.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

import SwiftUI
import Firebase

/// ImageView provides the main content for the app. It displays a current image and provides
/// controls to change it by taking a new one with the camera, selecting one from the photo library
/// or downloading one from Firebase storage.
struct ImageView: View {
/// Manages retrieval and persistence of the current image.
@StateObject private var photoStore = ImageStore(storage: Storage.storage())

/// Indicates whether the user is selecting an image from the photo library.
@State var isSelectingImage = false

/// Indicates whether the user is taking an image using the camera.
@State var isTakingPhoto = false

/// Indicates whether a submenu that allows the user to choose whether to select or take a photo
/// should be visible.
@State var showUploadMenu = false

var body: some View {
NavigationView {
VStack {
Image(uiImage: photoStore.image ?? UIImage())
.resizable()
.aspectRatio(contentMode: .fit)
}
.navigationTitle("Firebase Storage")
.toolbar {
ToolbarItemGroup(placement: .bottomBar) {
if showUploadMenu {
Button("❌") {
showUploadMenu = false
}

Spacer()

Button("Take Photo") {
isTakingPhoto = true
}.sheet(isPresented: $isTakingPhoto) {
ImagePickerRepresentable(
source: .camera,
store: photoStore,
visible: $isTakingPhoto
) {
showUploadMenu = false
}
}.disabled(!UIImagePickerController.isSourceTypeAvailable(.camera))

Button("Select Image") {
isSelectingImage = true
}.sheet(isPresented: $isSelectingImage) {
ImagePickerRepresentable(
source: .photoLibrary,
store: photoStore,
visible: $isSelectingImage
) {
showUploadMenu = false
}
}
} else {
Button("Upload") {
showUploadMenu = true
}
Spacer()
Button("Download") {
photoStore.loadImage()
}
}
}
}
}
}
}

struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ImageView()
}
}
Loading