gpt4 book ai didi

ios - 将内容从 Firebase 拉入 Swift 的问题

转载 作者:行者123 更新时间:2023-11-28 14:27:42 31 4
gpt4 key购买 nike

enter image description here

我正试图从 Firebase 获取报价,但我很挣扎。当然,我也不知道我在做什么。我需要一些帮助!

在 Firebase 中,我的报价设置如下:

root --> quotes --> quoteID --> quoteText, quoteAttribution

我正在尝试从 Firebase 中提取引号,将它们添加到本地数组(稍后放入字典),然后随机提取一个以在应用程序中使用。我希望将quoteText放入quoteLabel.text,将quoteAttribution放入authorLabel.text。我在另一个 StackOverflow 问题中找到了这个解决方案,但它在第 43 行抛出以下错误:

Could not cast value of type 'NSNull' (0x10f549740) to 'NSDictionary' (0x10f549178). 2018-07-21 22:49:50.241473-0400 Wavefully[72475:1126119] Could not cast value of type 'NSNull' (0x10f549740) to 'NSDictionary' (0x10f549178).

对于如何从 Firebase 中提取 quoteTextquoteAttribution 以在我的应用程序中使用,是否有人有任何提示?


这是我的代码:

class ViewController: UIViewController {

class quoteClass {
var uid = ""
var quote = ""
var author = ""
}

@IBOutlet weak var quoteLabel: UILabel!
@IBOutlet weak var authorLabel: UILabel!

var ref: DatabaseReference?
var databaseHandler: DatabaseHandle?

var quotesArray = [quoteClass]()

override func viewDidLoad() {
super.viewDidLoad()

// Set the reference to Firebase
ref = Database.database().reference()

let quotesRef = ref?.child("quotes")
quotesRef?.observeSingleEvent(of: .value, with: { (snapshot) in
for _ in snapshot.children {
let quoteSnap = snapshot
let quoteKey = quoteSnap.key

let thisQuoteRef = quotesRef?.child("quoteID")
thisQuoteRef?.observeSingleEvent(of: .value, with: { (quoteSnap) in
let singlequoteSnap = quoteSnap
let quoteDict = singlequoteSnap.value as! [String:AnyObject]
let quote = quoteDict["quoteText"]
let author = quoteDict["quoteAttribution"]

let aQuote = quoteClass()
aQuote.uid = quoteKey
aQuote.quote = quote as! String
aQuote.author = author as! String

print(aQuote.quote)
print(aQuote.author)
print(aQuote.uid)

self.quotesArray.append(aQuote)
})
}
})

let singleQuote = quotesArray.randomItem()!
print(singleQuote.uid)
print(singleQuote.quote)
print(singleQuote.author)}}

非常感谢您的帮助!

最佳答案

或者,您也可以通过将数据转换为 NSDictionary 来使用您的数据,如下所示:

        let dictionary = snapshot.value as? NSDictionary
let quote = dictionary["quoteText"] as? String ?? ""

关于ios - 将内容从 Firebase 拉入 Swift 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51461658/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com