我有一個 iOS 小部件,我想在從 Firestore 檢索資料后更新小部件視圖。我已經瀏覽了整個互聯網,包括這個問題。檢索資料后,我無法更新視圖。請查看小部件視圖的以下代碼。資料已被檢索,但在檢索資料后,我無法按照自己的意愿更新 UI 元素。
struct Runner_WidgetEntryView: View {
@State var text = ""
@State var textLoaded = false
var entry: Provider.Entry
var body: some View {
ZStack {
Image("back").resizable().scaledToFit()
Rectangle().foregroundColor(.black).cornerRadius(10).padding([.leading, .trailing], 10).padding([.top, .bottom], 15).overlay(Text(textLoaded ? text : "Loading..."))
}.onAppear {
let dispatchGroup = DispatchGroup()
FirebaseApp.configure()
let db = Firestore.firestore()
dispatchGroup.enter()
db.collection("collection").getDocuments { (snapshot, error) in
if error != nil {
text = "There was an error retrieving the text."
dispatchGroup.leave()
}
if let snapshot = snapshot {
for document in snapshot.documents {
if document.documentID == "Document ID" {
text = document.data()["qoute_name"] as! String
dispatchGroup.leave()
}
}
}
else {
text = "There was an error retrieving the text."
dispatchGroup.leave()
}
}
dispatchGroup.notify(queue: .main) {
textLoaded = true
}
}
}
}
檢索資料后如何更新 TextView?提前致謝。
uj5u.com熱心網友回復:
SwiftUI 需要在主執行緒上更新其變數。因此,如果您沒有看到更新,則可能是由于涉及的執行緒不同。試試這個來更新text主執行緒。
編輯-1:
.onAppear {
var fireTxt = "" // <-- here
let dispatchGroup = DispatchGroup()
FirebaseApp.configure()
let db = Firestore.firestore()
dispatchGroup.enter()
db.collection("collection").getDocuments { (snapshot, error) in
if error != nil {
fireTxt = "There was an error retrieving the text." // <-- here
}
if let snapshot = snapshot {
fireTxt = "No document found" // <-- here default text
for document in snapshot.documents {
if document.documentID == "Document ID" {
fireTxt = document.data()["qoute_name"] as! String // <-- here
}
}
}
else {
fireTxt = "There was an error retrieving the text." // <-- here
}
dispatchGroup.leave()
}
dispatchGroup.notify(queue: .main) {
textLoaded = true
text = fireTxt // <-- here on the main thread
}
}
請注意,在.onAppear. 您應該為此使用視圖模型。
uj5u.com熱心網友回復:
在建立@workingdog 的回答和大量測驗之后,我想出了這個解決方案:
SwiftUI 狀態無法從閉包中更新,因此無法從內部dispatchGroup.notify或任何其他閉包中更新。
解決方法是在創建時間線時從 Firebase 檢索資料,然后將檢索到的資料保存到UserDefaults. 從那里,可以在 SwiftUI 視圖UserDefaults中的onAppear方法中讀取資料。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/401562.html
標籤:ios 火力基地 谷歌云firestore 迅捷
