【发布时间】:2018-10-31 17:49:35
【问题描述】:
我有一个UICollectionView which looks like this image 并有以下data structure in Firebase。
我希望用户能够从收藏视图中删除单个帖子,然后从 firebase 中删除。我在其他 stackoverflow 帖子上看到说 我必须使用 firebase 中的 .removeValue,但 不知道如何获取对随机子项的引用才能删除它.
如何访问每个帖子的 autoId 值,例如“LPmNrvzu-aXsw_u-rEF”,以便从 Firebase 中删除该子节点?
这是我用来从 Firebase 加载所有用户帖子的路径:
@objc func observeUserPosts() {
let uid = Auth.auth().currentUser?.uid
let postsRef = Database.database().reference().child("posts").queryOrdered(byChild: "author/userid")
postsRef.queryEqual(toValue: uid!).observe(.value) { (snapshot) in
}
}
这是我加载所有 UICollectionView 代码的扩展
//extension - UICollectionView for user's posts
extension ProfileViewController: UICollectionViewDataSource,UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return postsuser.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell: PostsCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "postsCell", for: indexPath) as! PostsCollectionViewCell
cell.set(post: postsuser[indexPath.row])
cell.deletePostButton.addTarget(self, action: #selector(buttonAction), for: .touchUpInside)
cell.deletePostButton.tag = indexPath.row
return cell
}
@objc func buttonAction(sender: UIButton) {
Database.database().reference().child("posts").queryOrdered(byChild: "author/userid").observe(.value) { (snapshot) in
if let posts = snapshot.value as? [String: AnyObject] {
for (key, _) in posts {
// NOW HOW DO I REFERENCE THE CELL THAT THE USER CLICKS TO DELETE?
}
}
}
// postsuser[sender.tag]
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let vc = storyboard?.instantiateViewController(withIdentifier: "profileUsersSelectedPostViewController") as? ProfileUsersSelectedPostViewController
self.navigationController?.pushViewController(vc!, animated: true)
vc?.selectedpostsuser = postsuser[indexPath.row]
}
}
【问题讨论】:
标签: ios swift firebase firebase-realtime-database uicollectionviewcell