首先我想说,我问,因为如果我搞砸了,那么整个用户群就不见了!
如果用户更改了他的个人资料图片,我试图在帖子属于当前用户时更新帖子中的键值对,因为如果用户在发布后更改了他的图像,我不知道显示最新图像的其他方法。
所以我想出了这个,我想知道,这是正确的方法吗?
FIRDatabase.database().reference().child("posts")
.queryOrdered(byChild: "username")
.queryEqual(toValue: self.currentUser.generalDetails.userName)
.observeSingleEvent(of: .value, with: { snapshot in
if let snapDict = snapshot.value as? [String:AnyObject] {
for each in snapDict {
FIRDatabase.database().reference().child("posts/\(each.key)")
.updateChildValues(["profileImageUrl" : downloadUrl!.absoluteString])
}
}
})
如果结构是这样的:
posts //All posts
-KVfMmYqMny0n0_5gx9t //Post autogenerated key
comments
profileImageUrl: "http://..."
username: "John"
答案 0 :(得分:1)
回应OP的评论:
问题是如何使用他们制作的帖子更新用户个人资料图片,即使他们更改了图片。
这是一个用户节点
users
-YMka9s0okspoaSf
name: "Kirk"
profileImageURL: "http://"
-YJos09m0ao098Ko
name: "Spock"
profileImageURL: "http://"
然后是一个包含帖子的帖子节点,并保留对发布帖子的每个用户的引用
posts //All posts
-KVfMmYqMny0n0_5gx9t //Post autogenerated key
comment: "Yes, I love Italian, and so do you"
posted_by: "YMka9s0okspoaSf"
-KZKoa99jksoopd0a9Hq //Post autogenerated key
comment: "Yes"
posted_by: "YJos09m0ao098Ko"
然后最后一些过于冗长的代码加载帖子并从参考中捕获名称和图像
let postsRef = ref.child("posts")
let usersRef = ref.child("users")
postsRef.observeSingleEvent(of: .value, with: { snapshot in
for data in snapshot.children {
//convert the enumerator to a snapshot
let snap = data as! FIRDataSnapshot
//capture the value as a dictionary of String:String key:value pairs
let dict = snap.value! as! [String:String]
//grab the uid of the user that made the post
let uid = dict["posted_by"]!
let comment = dict["comment"]!
//craft a reference to the user that made the post
let thisUserRef = usersRef.child(uid)
//read in the users name once and print it
thisUserRef.observeSingleEvent(of: .value, with: { snapshot in
let dict = snapshot.value as! [String:String]
let name = dict["name"]! as String
let imageRef = dict["profileImageURL"]! as String
//on this line, load the image and display it
//then print the user and their comment
print("User \(name) said \(comment))
})
}
})
这项技术将始终保持用户图像新鲜,并在他们更改时与帖子绑定。
您可以简化它并直接在posts节点中保留对用户图像的引用,但我建议将uid保留在posts节点中,因为它更具查询性并且可以访问其他用户数据。
这将允许您,例如,允许用户阅读帖子点击用户名,看看他们最喜欢的食物是什么。