编辑(我希望这是更具体的):
当我运行应用程序时,我似乎无法从Firebase获取数据来显示页面:
将通知保存在firebase的子节点下时,将打印'objectId'-我想在另一个名为“ pinion”的节点(JSON firebase结构的代码段)下获取与此objectId匹配的节点下的数据是:
"notification" : {
"Gmg1ojNoBiedFPRNSL4sBZz2gSx2" : {
"-L_xNVcs7f3RhuLAcg7j" : {
"from" : "Gmg1ojNoBiedFPRNSL4sBZz2gSx2",
"objectId" : "-L_xNVcfZavjGFVv6iGs",
"timestamp" : 1552586771,
"type" : "pinion"
},
"pinions" : {
"Gmg1ojNoBiedFPRNSL4sBZz2gSx2" : {
"-L_xNVcfZavjGFVv6iGs" : {
"option A" : "Aaaa",
"option B" : "Cccc",
"question" : "Four",
"selectedId" : "FoFQDAGGX9hntBiBdXYCBHd8yas2",
"uid" : "Gmg1ojNoBiedFPRNSL4sBZz2gSx2"
},
"users" : {
"Gmg1ojNoBiedFPRNSL4sBZz2gSx2" : {
"email" : "eeee@gmail.com",
"fullname" : "Eeee",
"profileImageUrl" : "https://firebasestorage.googleapis.com/v0/b/pinion-4896b.appspot.com/o/profile_image%2FGmg1ojNoBiedFPRNSL4sBZz2gSx2?alt=media&token=209e57ca-b914-4023-8f85-fadfae7b7407",
},
非常感谢您的帮助,如果您需要其他任何信息,请告诉我-提前谢谢:)
更新:
它适用于问题和答案,但是调用图像时出现错误“无法在当前上下文中推断闭包类型”:
@IBOutlet weak var senderProfileImage: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
showImageOfSender()
}
var ref = Database.database().reference()
var userId = "" //this was made equal to the autoId under pinion, under the users ID in another view controller
func showImageOfSender() {
var senderPhoto = [String]()
guard let uid = Auth.auth().currentUser?.uid else {
return
}
let senderId = ref.child("pinions").child(uid).child(userId).child("uid")
ref.child("users").child(senderId).observeSingleEvent(of: .value, with: { snapshot in
//error is in the above line
let senderImage = snapshot.childSnapshot(forPath: "profileImageUrl").value as! String
senderPhoto.append(senderImage)
let senderImageUrl = URL.init(string: senderImage)
self.senderProfileImage.sd_setImage(with: senderImageUrl)
})
}
答案 0 :(得分:1)
我想这就是您的意思,首先导入Firebase:
import Firebase
然后获取数据库引用:
class PinionNotificationsViewController: UIViewController {
var ref: DatabaseReference!
...
}
然后,如果您知道UID,则函数可以如下所示:
func showQuestionAndAnswers() {
let uid = userId
ref = ref.child("pinions").child(uid)
ref.observeSingleEvent(of: .value, with: { (snapshot) in
// Get user value
let value = snapshot.value as? NSDictionary
let optionA = value?["option A"] as! String
let optionB = value?["option B"] as! String
print(optionA) // <- prints: "Bbbb"
print(optionB) // <- prints: "Dddd"
})
}
如果您不知道uid,就可以使用
ref = ref.child("pinions")
ref.observe(.childAdded) { (snapshot) in
// Get user value
let value = snapshot.value as? NSDictionary
let optionA = value?["option A"] as! String
// then you can append these values into an array it will go through all of them eg:
self.answersArray.append(optionA) // answers array will contain all optionA values from all children in the database under `"pinions"`
}
根据我的经验,这种方式将匹配数据库的顺序,因此在您的数组中,所有选项将按照其子级的顺序,就像它们在数据库中的顺序一样。
希望这会有所帮助!