簡體   English   中英

如何將實時 Firebase 數據庫中的數據保存到 Swift 中?

[英]How to save data from Real Time Firebase Database in Swift?

所以,在我的代碼中,你可以看到我想返回從 Firebase 檢索到的信息,但該方法總是返回一個空數組,我是 Swift 的新手,你能解釋一下為什么會發生這種情況,我該怎么做讓它起作用? 非常感謝。

var catalog:[String:NSDictionary] = [String():NSDictionary()]
func readCatalogInfo()->[String:NSDictionary]{
    
    let ref = Database.database(url: "https://reforestar-database-default-rtdb.europe-west1.firebasedatabase.app/").reference()
    
    _ = ref.child("trees").observe(.value, with: {snapshot in
        
        guard let information:[String:NSDictionary] = snapshot.value as? [String:NSDictionary] else {
            print("Error in getting information about the Trees")
            return
        }
        self.catalog = information
        
    })
    
    return self.catalog
}

這是代碼的圖片,如果您想看的話

數據庫請求異步工作,您必須添加一個完成處理程序。

並且不要在 Swift 中使用NS...集合類型

var catalog = [String:[String:Any]]()

func readCatalogInfo(completion: @escaping ([String:[String:Any]]) -> Void) {
    
    let ref = Database.database(url: "https://reforestar-database-default-rtdb.europe-west1.firebasedatabase.app/").reference()
    
    _ = ref.child("trees").observe(.value, with: {snapshot in
        
        guard let information = snapshot.value as? [String:[String:Any]] else {
            print("Error in getting information about the Trees")
            return
        }
        completion(information)
        
    })
    
}

並使用它

readCatalogInfo() { [weak self] result in 
   self?.catalog = result
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM