Firebase加载到不同节点iOS Swift

时间:2017-07-20 05:57:30

标签: ios swift xcode firebase

我正在尝试将描述,位置和Pic加载到同一个AutoId到firebase。我必须先存储Pic,然后获取URL,然后将URL添加到Pic值。我尝试先上传说明和位置,将Pic留空,然后返回并添加图片网址,但我的autoID的键值似乎不起作用。

它不断将Pic URL放入另一个childAutoId中。如何让它们存储到同一个子节点?

创建AutoID节点的初始功能

    @IBAction func postToWall(_ sender: Any) {
    let location : String = locationTextField.text!
    let description : String = descriptionTextField.text!


    self.ref.child("Posts").childByAutoId().setValue(["Location" : location, "Description" : description, "Pic" : ""])

    let newRef = ref.child("Posts").childByAutoId()
    print(newRef)
    key = newRef.key
    print(key)
    savePicPost()
}

将图片保存到存储空间后,尝试返回刚刚创建的ID并保存图片网址

    func savePicPost(){
    //Store the image in storage
    let imageName = NSUUID().uuidString
    let storedImage = storageRef.child("PostPics/").child(imageName)

    if let uploadData = UIImagePNGRepresentation(self.postImage.image!) {
        storedImage.putData(uploadData, metadata: nil, completion: { (metadata, error) in

            if error != nil {
                print(error!)
                return
            }

            if let picPostURL = metadata?.downloadURL()?.absoluteString {
                self.ref.child("Posts").child(self.key).updateChildValues(["Pic" : picPostURL], withCompletionBlock: { (error, ref) in

                    if error != nil{
                        print(error!)
                        return
                    }

                })
            }

        })
    }
}

以下是它如何保存到不同的ID中 Firebase Screenshot

我很亲近,我能感受到它。我认为,有些东西必须与我的关键价值一致。任何帮助将不胜感激。

由于

2 个答案:

答案 0 :(得分:1)

它清晰简单。您在key中存储了一个全新的孩子,而不是您在设置值时使用的孩子。

// This creates a new child
let newRef = ref.child("Posts").childByAutoId()

相反,请继续保留对childByAutoId的引用,并将其传递给savePicPost()。在那里你可以用它来存储你的图片网址。即。

let post = self.ref.child("Posts").childByAutoId()
post.setValue(["Location" : location, "Description" : description, "Pic" : ""])

// call your method like so
func savePicPost(into: post)

// use this ref to update picture URL
post.updateChildValues(["Pic" : picPostURL])

我希望它有所帮助。

答案 1 :(得分:0)

是的我现在看到了。谢谢。我正在创建一个新ID,而不是使用旧ID。这是我的代码现在的样子,我注释掉了我删除的内容。我实际上删除了一些使它工作。有趣的是如何。感谢

@IBAction func postToWall(_ sender: Any) {
    let location : String = locationTextField.text!
    let description : String = descriptionTextField.text!

//让newRef = ref.child("帖子")。childByAutoId()         让newRef = self.ref.child("帖子")。childByAutoId()

// self.ref.child("帖子")。childByAutoId()。setValue([" Location":location," Description":description, " Pic":""])

    newRef.setValue(["Location" : location, "Description" : description, "Pic" : ""])


    print(newRef)
    key = newRef.key
    print(key)
    savePicPost()

// print(key)

}