ios - 如何使用 Swift 5 从 Firebase 的快照中保存数据?

标签 ios swift firebase firebase-realtime-database

我正在尝试将从快照中获取的数据保存到不同的变量中。

我有一个名为 QuotesModel 的类,它具有作为字符串变量的 QuoteID 和 Quote。我正在尝试将报价的快照保存到该类中的 Quote 变量。

Database Image

class QuotesModel:NSObject {
    var QuoteID:String = ""
    var quote:String = ""
}



var rootref: DatabaseReference?
var QuotesArr = [QuotesModel]()

override func viewDidLoad() {
    rootref = Database.database().reference()
    let ref = rootref!.child("HelloWorld")
    super.viewDidLoad()

ref.observe(.childAdded, with: {(snapshot) in
    print(snapshot)
    guard let dictionary = snapshot.value as? [String : AnyObject] 
    else {
            return
     }
        let Obj = QuotesModel()
        Obj.QuoteID = snapshot.key
        Obj.quote = (dictionary["Test1"] as? String)!
        self.QuotesArr.append(Obj)
    }, withCancel: nil)
}

最佳答案

让我们把它清理干净,然后 make 也是 Swifty。

首先定义你的类和数组。我们将向类添加逻辑以将快照“分解”为其组件,并添加一些错误检查以防引用为 nil。

class QuoteModel {
    var quoteID = ""
    var quote = ""

    init(withSnapshot: DataSnapshot) {
        self.quoteId = withSnapshot.key
        self.quote = withSnapshot.value as? String ?? "No Quote"
    }
}

然后是对我们的根数据库和数组的引用。请注意,通常最佳做法是使用“self”来引用类变量。并且小写通常用于变量,大写用于类定义。

var rootref: DatabaseReference?
var quotesArr = [QuoteModel]()

然后是遍历所有引号并填充数组的代码

func iterateOverAllQuotes() {
    self.rootref = Database.database().reference()
    let ref = self.rootref!.child("HelloWorld")
    super.viewDidLoad()

    ref.observe(.childAdded, with: { snapshot in
        let aQuote = QuoteModel(withSnapshot: snapshot)
        self.quotesArr.append(aQuote)
    })
}

关于ios - 如何使用 Swift 5 从 Firebase 的快照中保存数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57021836/

相关文章:

ios - UIScrollView 自定义分页

swift - 我需要多个 Firebase 数据库引用吗?

ios - React Native-在图像中加载本地镜像

iphone - 我想在 NSObject 类中添加 MBProgressHUD

ios - 将 UITabBar 放置在 swift 的顶部

ios - UIBarButtonItem 不显示 ios 8

javascript - 带角色的Firestore查询?

javascript - Firebase-Function - 计划函数不断抛出错误 "UNAUTHENTICATED"

ios - React-Native IOS 构建在 pod 安装时出现错误。?

ios - 当 AdMob 中的 GADRewardBasedVideoAd 关闭时,选项卡 Controller 也会关闭