Swift: Firebase Chat App Part 9 - Upload Photos to Firebase Storage (Real-time) - Xcode 11 - 2020
import Foundation
import FirebaseStorage
final class StorageManager {
static let shared = StorageManager()
private init() {}
private let storage = Storage.storage().reference()
/*
/images/{email}_profile_picture.png
*/
/// Uploads picture to firebase storage and returns completionHandler with URLString to download
typealias UploadPictureCompletionHandler = (Result<String, Error>) -> Void
func uploadProfilePicture(with data: Data,
fileName: String,
completionHandler: @escaping UploadPictureCompletionHandler) {
storage.child("images/\(fileName)").putData(data, metadata: nil) { metadata, error in
guard
let metadata = metadata,
error == nil else {
completionHandler(.failure(StorageErrors.failedToUpload))
return
}
let reference = self.storage.child("images/\(fileName)").downloadURL { url, error in
guard
let url = url,
error == nil else {
completionHandler(.failure(StorageErrors.failedtToGetDownloadUrl))
return
}
let urlString = url.absoluteString
print("downloaded urlString: " + urlString)
completionHandler(.success(urlString))
}
}
}
enum StorageErrors: LocalizedError {
case failedToUpload
case failedtToGetDownloadUrl
}
}
DatabaseManager.shared.insertUser(with: chatUser) { [weak self] success in
guard let self = self else { return }
if success {
guard
let image = self.imageView.image,
let data = image.pngData() else {
return
}
let fileName = chatUser.profilePictureUrl
StorageManager.shared.uploadProfilePicture(with: data, fileName: fileName) { result in
switch result {
case .success(let downloadUrl):
UserDefaults.standard.set(downloadUrl, forKey: "profile_picture_url")
print(downloadUrl)
case .failure(let error):
print(error.localizedDescription)
}
}
}
}
struct ChatAppUser {
let firstName: String
let lastName: String
let emailAddress: String
let platform: Platform
var userIdentifier: String? = nil
var safeEmail: String {
return platform.rawValue.lowercased() + emailAddress.convertedPath
}
var profilePictureUrl: String {
return "\(safeEmail)_profile_picture.png"
}
}
Without exaggeration, I will say that this topic is one of the most interesting for me. Yes, I am passionate about creating visual content. One of my friends, he is a professional photographer, advised me to blog.depositphotos.com I would like to note right away that here I find absolutely free, but mega-important and useful articles for a modern person. Now I know the graphic design trends 2023, especially when it comes to infographics. In this case, I stand out among other specialists in this field.