London Escorts sunderland escorts 1v1.lol unblocked yohoho 76 https://www.symbaloo.com/mix/yohoho?lang=EN yohoho https://www.symbaloo.com/mix/agariounblockedpvp https://yohoho-io.app/ https://www.symbaloo.com/mix/agariounblockedschool1?lang=EN
3.1 C
New York
Friday, January 31, 2025

ios – The best way to Add profileImage to Firestore Database?


i make the register consumer in firebase

in registerViewcontroller

i’ve username, e mail, password and profileImage

enter image description here

beneath picture is Firestore constructionenter image description here

that is what i save consumer info in firestore database

right here is drawback

when i choose profileimage, username, e mail, password and faucet signup button

drawback comes out

enter image description here

the issue is didn’t add profile picture to firestore database

and console says

“userImage: <UIImage:0x600003000ea0 nameless {4032, 3024} renderingMode=automated(authentic)>

Firebase Storage 업로드 실패: Object profile_images/rRMJBmF4NlYnlOmVxawxGZqkwzu2.jpg doesn’t exist.”

Code Performance Rationalization

Person Registration (registerUser)

  • Makes use of Firebase Auth to create a consumer account with an e mail and password.

  • Upon profitable creation, retrieves the userUID.

Profile Picture Add and Firestore Save (uploadProfileAndSaveUserToFirestore)

  • Uploads the profile picture to Firebase Storage.

  • Retrieves the obtain URL after the add is full.

  • Saves the e mail, username, and profileImageURL within the Firestore customers assortment below the corresponding consumer UID.

Firestore Person Info Save (saveUserToFirestore)

  • Shops the username, e mail, and profileImageURL fields together with the createdAt timestamp in Firestore.

that is my registeruser construction

import Basis
import UIKit

struct RegisterUserRequest {
    
    let username: String
    let e mail: String
    let password: String
    
    var userImage: UIImage
    
}

that is my authservice class

func registerUser(request: RegisterUserRequest, completion: @escaping (Bool, Error?) -> Void) {
        // 1. Firebase Auth로 사용자 생성
        Auth.auth().createUser(withEmail: request.e mail, password: request.password) { authResult, error in
            if let error = error {
                print("Firebase Auth 사용자 생성 실패: (error.localizedDescription)")
                completion(false, error)
                return
            }
            
            guard let userUID = authResult?.consumer.uid else {
                let uidError = NSError(area: "", code: -1, userInfo: [NSLocalizedDescriptionKey: "사용자 UID를 가져올 수 없습니다."])
                completion(false, uidError)
                return
            }
            
            // 2. 이미지 업로드와 Firestore 데이터 저장 통합
            self.uploadProfileAndSaveUserToFirestore(userUID: userUID, request: request) { success, error in
                if success {
                    print("회원가입 성공")
                    completion(true, nil)
                } else {
                    print("회원가입 실패: (error?.localizedDescription ?? "알 수 없는 에러")")
                    completion(false, error)
                }
            }
        }
    }

    personal func uploadProfileAndSaveUserToFirestore(userUID: String, request: RegisterUserRequest, completion: @escaping (Bool, Error?) -> Void) {
        // 1. 이미지를 Firebase Storage에 업로드
        guard let imageData = request.userImage.jpegData(compressionQuality: 0.8) else {
            completion(false, NSError(area: "", code: -1, userInfo: [NSLocalizedDescriptionKey: "이미지 데이터를 변환할 수 없습니다."]))
            return
        }
        
        let storageRef = Storage.storage().reference().baby("profile_images/(userUID).jpg")
        storageRef.putData(imageData, metadata: nil) { metadata, error in
            if let error = error {
                print("Firebase Storage 업로드 실패: (error.localizedDescription)")
                completion(false, error)
                return
            }
            
            // 2. 다운로드 URL 가져오기
            storageRef.downloadURL { url, error in
                if let error = error {
                    print("Firebase Storage 다운로드 URL 가져오기 실패: (error.localizedDescription)")
                    completion(false, error)
                    return
                }
                
                guard let profileImageURL = url?.absoluteString else {
                    completion(false, NSError(area: "", code: -1, userInfo: [NSLocalizedDescriptionKey: "이미지 URL을 가져올 수 없습니다."]))
                    return
                }
                
                // 3. Firestore에 사용자 정보 저장
                self.saveUserToFirestore(userUID: userUID, username: request.username, e mail: request.e mail, profileImageURL: profileImageURL) { success, error in
                    completion(success, error)
                }
            }
        }
    }

    personal func saveUserToFirestore(userUID: String, username: String, e mail: String, profileImageURL: String, completion: @escaping (Bool, Error?) -> Void) {
        let db = Firestore.firestore()
        
        let userData: [String: Any] = [
            "username": username,
            "email": email,
            "profileImageURL": profileImageURL,
            "createdAt": Timestamp()
        ]
        
        db.assortment("customers").doc(userUID).setData(userData) { error in
            if let error = error {
                print("Firestore 저장 실패: (error.localizedDescription)")
                completion(false, error)
            } else {
                print("Firestore 저장 성공")
                completion(true, nil)
            }
        }
    }

in registerController

beneath code is PHPickerViewControllerDelegate

extension RegisterController: PHPickerViewControllerDelegate {
    func picker(_ picker: PHPickerViewController, didFinishPicking outcomes: [PHPickerResult]) {
        
        // PHPicker 닫기
        picker.dismiss(animated: true)
        
        // 첫 번째 선택된 아이템 가져오기
        let itemProvider = outcomes.first?.itemProvider
        
        if let itemProvider = itemProvider, itemProvider.canLoadObject(ofClass: UIImage.self) {
            // UIImage 불러오기
            itemProvider.loadObject(ofClass: UIImage.self) { (picture, error) in
                if let picture = picture as? UIImage { // 불러온 이미지 타입 확인
                    DispatchQueue.principal.async {
                        // CustomImageView에 이미지 설정
                        self.profileImage = picture
                        self.userPofileView.setImageType(.consumer(picture))
                    }
                } else {
                    print("이미지가 올바르지 않습니다.")
                }
            }
        } else {
            print("이미지를 불러올 수 없습니다.")
        }
    }
}

beneath code is when i faucet enroll button for run

in right here profileImage goes to userImage

// MARK: - Selectors
    @objc personal func didTapSignUp() {
        let username = self.usernameField.textual content ?? ""
        let e mail = self.emailField.textual content ?? ""
        let password = self.passwordField.textual content ?? ""
        let userImage = profileImage ?? UIImage()
        
        let registerUserRequest = RegisterUserRequest(username: username,
                                                      e mail: e mail,
                                                      password: password,
                                                      userImage: userImage)
        
        print("userImage: (userImage)")
        
        // Examine Username
        if !Validator.isValidUsername(for: registerUserRequest.username) {
            AlertManager.showInvalidUsernameAlert(on: self)
            return
        }
        
        // Examine E-mail
        if !Validator.isValidEmail(for: registerUserRequest.e mail) {
            AlertManager.showInvalidEmailAlert(on: self)
            return
        }
        
        // Examine Password
        if !Validator.isValidPassword(for: registerUserRequest.password) {
            AlertManager.showInvalidPasswordAlert(on: self)
            return
        }
        
        AutheService.shared.registerUser(request: registerUserRequest) { wasRegistered, error in
            
            if let error = error {
                AlertManager.showSignInErrorAlert(on: self, with: error)
                return
            }
            
            if wasRegistered {
                if let sceneDelegate = self.view.window?.windowScene?.delegate as? SceneDelegate {
                    sceneDelegate.checkAuthentication()
                }
            } else {
                AlertManager.showSignInErrorAlert(on: self, with: NSError(area: "", code: 500, userInfo: [NSLocalizedDescriptionKey: "회원가입 실패"]))
            }
        }
    }

Related Articles

Social Media Auto Publish Powered By : XYZScripts.com