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

时间:2020-03-13 18:50:45

标签: ios swift firebase firebase-realtime-database firebase-storage

当我的用户注册时,他们使用的配置文件图像直接进入了Firebase。图像已正确上传到Firebase存储中,但是一旦它出现在数据库中,配置文件图像URL也会在调试区域中丢失,该图像链接显示为可选。我应该在此代码中进行哪些更改,以将图像链接正确上传到Firebase数据库中?

  if let AuthData = AuthDataResult {
                  print(AuthData.user.email)
                      var dict : Dictionary < String, Any> = [
                        "uid": AuthData.user.uid,
                          "username": self.UsernameTextField.text!,
                      "email": AuthData.user.email,

"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)
                }

                Database.database().reference().child("users").child(AuthData.user.uid).updateChildValues(dict, withCompletionBlock: { (error,ref) in
                    if error == nil {
                        print("Done")
                        return
                    }

2 个答案:

答案 0 :(得分:1)

问题中的所有代码似乎都在AuthData变量内。

此问题是由以下某个键引起的: dict var中的值对为空字符串。我将其缩短一些以突出该问题。这是原始代码,加上我的注释:

 if let AuthData = AuthDataResult {
    var dict : Dictionary < String, Any> = [
        "uid": AuthData.user.uid,
        "username": self.UsernameTextField.text!,
        "email": AuthData.user.email,
        "ProfileImageUrl": "",  // <--- Profile ImageUrl is an empty string
    ]

    imageReference.putData(uploadData, metadata: metaDataForImage) { (meta, err) in
        if let err = err{
        } else {
            imageReference.downloadURL { (url, err) in
                if let err = err{
                } else {
                    let urlString = url?.absoluteString
                }

                //The ProfileImageUrl key: value pair within the **dict** var is an
                //  empty string at this point, so no url is written.
                let dbRef = Database.database().reference()
                let usersRef = dbRef.child("users").child(AuthData.user.uid)
                usersRef.updateChildValues(dict, withCompletionBlock: { (error,ref) in
                   if error == nil {
                      print("Done")
                      return
                   }
                   //note that if an error occurs, the code silently fails

要解决此问题,请用您要写入的数据填充字典。

这是代码的更正部分,其中包括错误检查和使用下载URL填充ProfileImageUrl,然后将其写入Firebase。

imageReference.downloadURL { (url, error) in
    if let err = error {
        print(err.localizedDescription)
        return
    }

    guard let validUrl = url else {
        print("url was not valid")
        return
    }

    let urlString = validUrl.absoluteString
    dict["ProfileImageUrl"] = urlString //update the dict with the url

    let dbRef = Database.database().reference()
    let usersRef = dbRef.child("users").child(AuthData.user.uid)
    usersRef.updateChildValues(dict, withCompletionBlock: { error, ref in
        if let err = error {
            print(err.localizedDescription)
            return
        }

        print("Successfully wrote auth data and url")
    })
}

答案 1 :(得分:0)

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

plt3 = plt + p9.scale_fill_desaturate(color="blue", guide=False)