首页 > 解决方案 > 挣扎于基本的 Swift 逻辑(使用常量、变量和循环)

问题描述

我想使用从 firebase 获得的两个“循环”中的 2 个字符串,并在另一个“循环”中使用它们以将它们与一堆其他信息一起上传。

我的问题是,我无法将下载的值fullnamepfp下载的值上传到firebase。

关于如何解决这个问题的任何想法?

func sendToFire(){
    let combined = "\(userID)" + "\(number)"
    let docRef = db.collection("posts").document(combined)
    let description = self.textPost.text
    let nameRef = db.collection("users").document(userID)
    var fullname = ""
    var pfp = ""

    if fireImage == nil {

       nameRef.getDocument { (document, error) in
           if let document = document{
               fullname = document.get("fullname") as! String
           }else{
               print("Coulnt get fullname")
           }
       }

       nameRef.getDocument { (document, error) in
           if let document = document{
               pfp = document.get("profileimage") as! String
           }else{
               print("Couldn't get profileimage")
           }
       }

       docRef.getDocument { (document, error) in
           if let document = document, document.exists {
               print("Post ID already taken")
           } else {
               print("Post Document gets created")
               self.db.collection("posts").document(combined).setData([
                   "description": description!,
                   "likes": self.likes,
                   "postType": 0,
                   "profileImage": pfp,
                   "time": self.date,
                   "uid": self.userID,
                   "username": fullname
               ]) { err in
                   if let err = err {
                       print("Error writing document: \(err)")
                   } else {
                       print("Post Document successfully written!")
                   }
               }
           }
       }
    }
}

标签: swiftfirebase

解决方案


加入document.existsif let

        nameRef.getDocument { (document, error) in
            if let document = document, document.exists{
                fullname = document.get("fullname") as! String
            }else{
                print("Coulnt get fullname")
            }
        }

        nameRef.getDocument { (document, error) in
            if let document = document, document.exists{
                pfp = document.get("profileimage") as! String
            }else{
                print("Couldn't get profileimage")
            }
        } 

检查响应中的实际键名fullnameprofileimage.


推荐阅读