首页 > 解决方案 > SwiftUI:如何在第二个视图中从 Firestore 检索数据?

问题描述

这是我的第一个 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-firestoreswiftuipicker

解决方案


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

@ObservedObject var foodDatas = FoodViewModel()

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

您可以将原始ContentView的副本FoodDataModel作为参数传递。

因此,我引用的前一行将变为:

@ObservedObject var foodDatas : FoodViewModel

然后你NavigationLink会看起来像这样:

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

推荐阅读