简体   繁体   English

无法从Firebase数据库检索数据

[英]Can't retrieve data from Firebase Database

I my code I can't retrieve data from Firebase. 我的代码无法从Firebase检索数据。

When I am adding values on Firebase I do see that items added on Firebase database on my console. 当我在Firebase上添加值时,我确实在控制台上看到在Firebase数据库上添加的项目。

Also I had created listener .childAdded and I see that items added on Firebase Database. 我还创建了侦听器.childAdded并且看到Firebase数据库中添加了该项目。

But when I call .value it retrieves nil result. 但是,当我调用.value它将检索nil结果。

I don't know what's happening there. 我不知道那里发生了什么。

Here is my code. 这是我的代码。

class FirebaseManager {

    var ref: DatabaseReference?
    var database: DatabaseHandle?

    static let shared: FirebaseManager = {
        Database.database().isPersistenceEnabled = true
        return FirebaseManager()
    }()

    private func initFireabase() {
        ref =  Database.database().reference(withPath: AMUtils.getUDID())        
    }

    func addToDB(composition: Composition) {
        initFireabase()
        ref?.child(String(composition.id)).child("id").setValue(composition.id)
        ref?.child(String(composition.id)).child("title").setValue(composition.title)       
    }

    func removeFromDb(composition: Composition) {
        ref?.child(String(composition.id)).removeValue()
    }

    func getCompositonFromDB(onResult: @escaping ([Composition]) -> Void){
        initFireabase()
        var compositions: [Composition] = []
        database = ref?.observe(.value, with: { (snapshot) in
            compositions.removeAll()
            let value = snapshot.value as? JSON
            compositions.append(AudioListParser.parseObject(json: value!))
            self.ref?.removeObserver(withHandle: self.database!)
            onResult(compositions)
        })
    }
}

getCompositonFromDB() I am calling when I am starting the view controller and this is always nil even I have values on database getCompositonFromDB()我在启动视图控制器时正在调用,即使我在数据库中有值,这始终为nil

Could anyone tell me what I did wrong here? 谁能告诉我我在这里做错了什么?

在此处输入图片说明

have you changed the rules for database?? 您是否更改了数据库规则? like if you are authenticating you should set not null for both write and read and if you are not authenticating then keep it null for both, because doing exact opposite of above could cause some errors!! 例如,如果您要进行身份验证,则不应该将读写都设置为null;如果您不进行身份验证,则应将两者都设置为null,因为执行与上述操作相反的操作可能会导致某些错误!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM