[UIKit] Firebase Chat App: Photo Upload

Junyoung Park·2022년 9월 19일
0

UIKit

목록 보기
39/142
post-thumbnail

Swift: Firebase Chat App Part 9 - Upload Photos to Firebase Storage (Real-time) - Xcode 11 - 2020

Firebase Chat App: Photo Upload

구현 목표

  • 파이어베이스 스토리지 사진 업로드
  • 유저 디폴트 사진 URL 저장

구현 태스크

  1. 파이어베이스 스토리지 매니저 클래스
  2. 유저 사진 등록 → 유저 디폴트 파이어베이스 이미지 URL 저장

핵심 코드

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)
                        }
                    }
                }
            }
  • 사진 데이터 → 파이어베이스 스토리지 등록
  • 스토리지 등록 성공 시 해당 URL 주소를 유저 디폴트에 저장(덮어쓰기 가능)
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"
    }
}
  • 연산 프로퍼티를 통해 이메일을 사용한 프로필 URL 주소 리턴
profile
JUST DO IT

1개의 댓글

comment-user-thumbnail
2023년 9월 21일

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.

답글 달기