如何从 Firebase (Swift) 中删除一个孩子 [英] How to delete a child from Firebase (Swift)

查看:21
本文介绍了如何从 Firebase (Swift) 中删除一个孩子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在学习有关制作 instragram 式应用程序的教程,但在弄清楚如何从 Firebase 和提要中删除帖子时遇到了很多麻烦.用户选择或拍摄的图像通过此功能上传到 Firebase 数据库:

I've been following a tutorial on making an instragram-esque app, and I'm having a lot of trouble figuring out how to delete a post, both from Firebase and from the feed. The image that the user selects or takes is uploaded to Firebase database with this function:

func uploadToFirebase() {
    AppDelegate.instance().showActivityIndicator()

    let uid = FIRAuth.auth()!.currentUser!.uid
    let ref = FIRDatabase.database().reference()
    let storage = FIRStorage.storage().reference(forURL: "gs://cloudcamerattt.appspot.com")

    let key = ref.child("posts").childByAutoId().key
    let imageRef = storage.child("posts").child(uid).child("(key).jpg")

    let data = UIImageJPEGRepresentation(self.previewImage.image!, 0.6)

    let uploadTask = imageRef.put(data!, metadata: nil) { (metadata, error) in

        if error != nil {
            print(error!.localizedDescription)
            AppDelegate.instance().dismissActivityIndicator()
            return
        }

        imageRef.downloadURL(completion: { (url, error) in

            if let url = url {
                // how do I add date: NSDate in here?
                let feed = ["userID" : uid,
                            "pathToImage" : url.absoluteString,
                            "likes" : 0,
                            "author" : FIRAuth.auth()!.currentUser!.displayName!,
                            "postID" : key] as [String : Any]

                let postFeed = ["(key)" : feed]

                ref.child("posts").updateChildValues(postFeed)
                AppDelegate.instance().dismissActivityIndicator()

                self.dismiss(animated: true, completion: nil)
            }
        })
    }
    uploadTask.resume()
}

最终在 Firebase 中看起来像这样:

Which ends up in Firebase looking like this:

根据我找到的堆栈溢出答案,我尝试设置一个在按下删除按钮时调用的删除函数.此删除按钮位于照片详细信息"视图上,用户可以通过点击图像源中的图像来访问该视图 - 此照片详细信息视图以更大的尺寸显示图像,以及一些其他信息,例如喜欢:

Following a stack overflow answer I found, I tried to set up a delete function to be called when the delete button is pressed. This delete button is on a "photo detail" view, which the user gets to by tapping an image in the image feed - this photo detail view displays the image in a bigger size, along with some other info such as likes:

func deletePost(firstTree: String, childIWantToRemove: String) {

    let uid = FIRAuth.auth()!.currentUser!.uid
    let ref = FIRDatabase.database().reference()
    let storage = FIRStorage.storage().reference(forURL: "gs://cloudcamerattt.appspot.com")

    let key = ref.child("posts").childByAutoId().key
    let imageRef = storage.child("posts").child(uid).child("(key).jpg")

    ref.child("posts").child(key).child("postID").removeValue { (error, ref) in
        if error != nil {
            print("error (error)")
        }
    }
}

并在此处调用函数:

@IBAction func moreButtonPressed(_ sender: AnyObject) {

    let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
    let cancelAction = UIAlertAction(title: "Cancel", style: .cancel)
    let destroyAction = UIAlertAction(title: "Delete", style: .destructive) { action in
        print(action)

        let ref = FIRDatabase.database().reference()
        let key = ref.child("posts").childByAutoId().key

        let firstTree = key
        let valueToRemove = "postID"
        self.deletePost(firstTree: firstTree, childIWantToRemove: valueToRemove)
    }

    alertController.addAction(destroyAction)
    alertController.addAction(cancelAction)
    self.present(alertController, animated: true)
}

虽然我不太明白我在做什么,不用说点击删除按钮基本上没有任何作用.谁能告诉我如何修复删除功能,以便我可以正确地从 firebase 中删除图像/帖子?

I'm not really understanding what I'm doing though, and needless to say tapping the delete button does essentially nothing. Can anyone show me how to fix the delete function so I can remove an image/post from firebase properly?

我的 PhotoDetailController 中有 var selectedPost: Post!,它是从 didSelectItem 中的 FeedViewController(图像提要)传递的,如下所示:

I have var selectedPost: Post! in my PhotoDetailController, which is passed from the FeedViewController (image feed) in didSelectItem like so:

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
    let photoDetailController = self.storyboard?.instantiateViewController(withIdentifier: "photoDetail") as! PhotoDetailController

    photoDetailController.selectedPost = posts[indexPath.row]

    present(photoDetailController, animated: true, completion: nil)
}

所以它有索引路径.关于上述函数的另一个注意事项是 var posts = [Post]() 在 FeedViewController 中实例化,所以这就是 posts[indexPath.row] 的来源.>

So it has the index path. Another note about the above function is that var posts = [Post]() is instantiated in the FeedViewController, so that's where posts[indexPath.row] comes from.

推荐答案

这应该可行.

func deletePost() {
  let uid = FIRAuth.auth()!.currentUser!.uid
  let storage = FIRStorage.storage().reference(forURL: "gs://cloudcamerattt.appspot.com")

  // Remove the post from the DB
  ref.child("posts").child(selectedPost.postID).removeValue { error in
    if error != nil {
        print("error (error)")
    }
  }
  // Remove the image from storage
  let imageRef = storage.child("posts").child(uid).child("(selectedPost.postID).jpg")
  imageRef.delete { error in
    if let error = error {
      // Uh-oh, an error occurred!
    } else {
     // File deleted successfully
    }
  }
}

还有 .childByAutoId().key 生成一个键来将项目插入到数据库中.您不能使用它来获取对现有项目的引用.

Also .childByAutoId().key generates a key to insert items into the DB. You can't use it get a reference to an existing item.

这篇关于如何从 Firebase (Swift) 中删除一个孩子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆