【问题标题】:SwiftUI: How to retrieve data from Firestore in second view?SwiftUI:如何在第二个视图中从 Firestore 检索数据?
【发布时间】:2021-05-29 21:00:28
【问题描述】:

这是我的第一个 SwiftUI 项目,在编程方面非常新。

我的内容视图有一个视图模型和一个选择器,设法将 $selection 发送到详细视图,但不知道如何让它再次从 Firestore 中读取。我有点觉得缺少了什么,就像我需要使用 if-else,但无法准确指出问题所在。在这里搜索了论坛,但似乎找不到解决方案。

这是虚拟机

import Foundation
import Firebase

class FoodViewModel: ObservableObject {

@Published var datas = [Food]()

private var db = Firestore.firestore()

func fetchData(){
    
    db.collection("meals").addSnapshotListener { (snap, err) in
        DispatchQueue.main.async {
        if err != nil {
            print((err?.localizedDescription)!)
            return
        } else {
        for i in snap!.documentChanges{
                
                let id = i.document.documentID
                let name = i.document.get("name") as? String ?? ""
                let weight = i.document.get("weight") as? Int ?? 0
                let temp = i.document.get("temp") as? Int ?? 0
                let time = i.document.get("time") as? Int ?? 0
                
                
                self.datas.append(Food(id: id, name: name, weight: weight, temp: temp, time: time))
            }
        }
        }
    }
}

}

struct ContentView: View {

@ObservedObject var foodDatas = FoodViewModel()

@State private var id = ""
@State public var selection: Int = 0

var body: some View {
    
    NavigationView{

        let allFood = self.foodDatas.datas

        ZStack {
            Color("brandBlue")
                .edgesIgnoringSafeArea(.all)
            VStack {
                Picker(selection: $selection, label: Text("Select your food")) {
                    ForEach(allFood.indices, id:\.self) { index in
                        Text(allFood[index].name.capitalized).tag(index)
                    }
                }
                .onAppear() {
                    self.foodDatas.fetchData()
                }

                Spacer()
                
                NavigationLink(
                    destination: DetailView(selection: self.$selection),
                    label: {
                        Text("Let's make this!")
                            .font(.system(size: 20))
                            .fontWeight(.bold)
                            .foregroundColor(Color.black)
                            .padding(12)
                    })
}

在选择器选择食物类型后,我希望它显示烹饪时间和温度等其余细节。现在它显示文本部分的“索引超出范围”。

import SwiftUI
import Firebase

struct DetailView: View {

@ObservedObject var foodDatas = FoodViewModel()

@Binding var selection: Int


var body: some View {
    
    NavigationView{
        
        let allFood = self.foodDatas.datas
        
        ZStack {
            Color("brandBlue")
                .edgesIgnoringSafeArea(.all)
            VStack {
                
                Text("Cooking Time: \(allFood[selection].time) mins")
                
            }

        }

    }
}

感谢我能得到的所有帮助。

【问题讨论】:

    标签: google-cloud-firestore swiftui picker


    【解决方案1】:

    在您的DetailView 中,您正在创建FoodViewModel 的新实例:

    @ObservedObject var foodDatas = FoodViewModel()
    

    那个新实例没有获取任何数据,因此选择的索引超出范围,因为它的数组是空的。

    您可以将原始ContentViewFoodDataModel 副本作为参数传递。

    所以,我引用的上一行将变为:

    @ObservedObject var foodDatas : FoodViewModel
    

    然后您的NavigationLink 将如下所示:

    NavigationLink(destination: DetailView(foodDatas: foodDatas, selection: self.$selection) //... etc
    

    【讨论】:

    • 谢谢,它现在获取数据!注意我的错误,再次感谢。
    猜你喜欢
    • 1970-01-01
    • 2019-08-07
    • 1970-01-01
    • 1970-01-01
    • 2020-11-21
    • 2023-01-09
    • 1970-01-01
    • 2021-10-26
    • 1970-01-01
    相关资源
    最近更新 更多