如何将个人资料图片网址上传到Firebase数据库

问题描述 投票:0回答:1

当我的用户注册时,他们使用的配置文件图像会直接发送到firebase。图像以正确的方式上传到Firebase存储中,但是一旦它出现在数据库中,配置文件图像URL就会丢失。我应该在此代码中进行哪些更改,以将图像链接正确上传到Firebase数据库中?

"ProfileImageUrl": "",
                      ]
            let storage = Storage.storage()
            let storageRef = storage.reference()
           let imageName = UUID().uuidString
             let imageReference = Storage.storage().reference().child(imageName)

             //2. Compress quality
            if let uploadData = self.ProfileImage.image?.jpegData(compressionQuality: 0.5){

                 //3. Save image as .jpeg
                 let metaDataForImage = StorageMetadata()
                 metaDataForImage.contentType = "image/jpeg"

                 //4. Add the data to Firebase Storage
                 imageReference.putData(uploadData, metadata: metaDataForImage) { (meta, err) in
                     if let err = err{
                         print(err.localizedDescription)
                     }
                     else{
                         //5. Retrieving the image URL
                         imageReference.downloadURL { (url, err) in
                             if let err = err{
                                 print(err.localizedDescription)
                             }
                             else{
                                 //6. Print the complete URL as string
                                 let urlString = url?.absoluteString
                                 print(urlString)
                             }
ios swift firebase firebase-realtime-database firebase-storage
1个回答
0
投票

我有根据的猜测是,您在上载尚未完成或尚未检索到下载URL时将用户信息写入数据库。上传URL和请求下载URL都是异步操作,这意味着依赖于它们完成的任何代码都必须是inside操作完成(或从那里调用)后执行的闭包。

let storage = Storage.storage()
let storageRef = storage.reference()
let imageName = UUID().uuidString
 let imageReference = Storage.storage().reference().child(imageName)

 //2. Compress quality
 if let uploadData = self.ProfileImage.image?.jpegData(compressionQuality: 0.5){

     //3. Save image as .jpeg
     let metaDataForImage = StorageMetadata()
     metaDataForImage.contentType = "image/jpeg"

     //4. Add the data to Firebase Storage
     imageReference.putData(uploadData, metadata: metaDataForImage) { (meta, err) in
         if let err = err{
             print(err.localizedDescription)
         }
         else{
             //5. Retrieving the image URL
             imageReference.downloadURL { (url, err) in
                 if let err = err{
                     print(err.localizedDescription)
                 }
                 else{
                     //6. Print the complete URL as string
                     let urlString = url?.absoluteString
                     print(urlString)

                     // 7. Write the URL to the database here <--
                 }
© www.soinside.com 2019 - 2024. All rights reserved.