我正试图从Firebase中获取报价,但我很挣扎。当然,我也不知道我在做什么。我可以帮忙!
在Firebase中,我的报价设置如下:
根 ->报价 -> quoteID -> quoteText,quoteAttribution
我正在尝试从Firebase中拉引号,将其添加到本地数组(以稍后放入字典中),然后拉一个随机的引号以在应用程序中使用。我希望将quoteText
放入quoteLabel.text
,并将quoteAttribution
放入authorLabel.text
。我在另一个StackOverflow问题中找到了该解决方案,但是它在第43行抛出了以下错误:
无法将类型'NSNull'(0x10f549740)的值强制转换为'NSDictionary'(0x10f549178)。 2018-07-21 22:49:50.241473-0400 Wavefully [72475:1126119]无法将类型'NSNull'(0x10f549740)的值强制转换为'NSDictionary'(0x10f549178)。
有人对我如何将quoteText
和quoteAttribution
从Firebase中拉出以在我的应用程序中使用有任何提示吗?
这是我的代码:
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)}}
非常感谢您的帮助!
答案 0 :(得分:1)
或者,您也可以通过将数据转换为NSDictionary
来使用数据,如下所示:
let dictionary = snapshot.value as? NSDictionary
let quote = dictionary["quoteText"] as? String ?? ""
答案 1 :(得分:0)
好的,所以我把它变得比原来更难了。我做到了,它正在起作用:
func grabData() {
ref = Database.database().reference()
ref?.child("quotes").observe(.value, with: {
snapshot in
for snap in snapshot.children.allObjects as! [DataSnapshot] {
guard let dictionary = snap.value as? [String:AnyObject] else {
return
}
let quote = dictionary["quoteText"] as? String
let author = dictionary["quoteAttribution"] as? String
let id = dictionary["quoteID"] as? String
self.quoteLabel.text = quote
self.authorLabel.text = author
print(quote!)
print(author!)
print(id!)
}
})
}
现在,我只需要致电grabData()
中的viewDidLoad
来获取报价。接下来:将显示的报价随机化。哦,可能将其存储在Core Data或Realm中以进行本地存储。
感谢您的光临!