如何从Firebase数据库中的子项添加数据?

时间:2016-09-02 10:53:26

标签: ios xcode firebase firebase-realtime-database collectionview

如何从Firebase数据库中的子项添加数据?以下是我的代码。

import UIKit
import Firebase
import FirebaseDatabase

class MedalViewController: UICollectionViewController {

    var imagesArray = [String]()
    var identities = [String]()
    var identities2 = [String]() //Creates an empty array 
    var imagesArrayGreyed = [String]()
    let databaseRef = FIRDatabase.database().reference()
    let userID = FIRAuth.auth()?.currentUser?.uid

    override func viewDidLoad() {
        super.viewDidLoad()
        imagesArray = ["1", "2", "3"] //Add all the medal images here
        identities = ["Shield", "Tie", "Star"] //Add all the identities here
        identities2 = ["Shield"] //Choose what medals the user has.
        imagesArrayGreyed = ["1Greyed","2Greyed","3Greyed"] //Add all the greyed images here

        databaseRef.child("users").child(userID!).observeSingleEventOfType(.Value, withBlock: { (snapshot) in
            // Get user value
            var newIdentities2 = snapshot.value!["medals"] as! String

            // how do I continue on from here?


            // ...
        }) { (error) in
            print(error.localizedDescription)
        }


    }

这是我的Firebase数据结构的图片:

Image

只有在打开ViewController后才能获取数据,然后将其附加到数组中。谢谢你的帮助。

编辑:目的是从firebase儿童奖牌获得数据'并将其附加到本地数组" identifier2"

1 个答案:

答案 0 :(得分:0)

databaseRef.child("users").child(userID!).observeSingleEventOfType(.Value, withBlock: { (snapshot) in
        // Get user value
        if let identities = snapshot.value! as? [String:AnyObject]{
                for each in identities.1 as String{
                   identifier2.append(each)//will append medals
                }
        }
        // ...
    }) { (error) in
        print(error.localizedDescription)
    }