繁体   English   中英

如何使用 Swift 中的 url 从 firebase 正确检索数据?

[英]How to retrieve data from firebase properly with a url in Swift?

我正在尝试从我的 firebase 实时数据库中检索数据,但我被以下代码困住了如何正确处理它。 我有一个 tableview 类别列表,当某个类别的 select 时,我想将作为来自数据库的data键值的特定数据显示到视图中。 可能吗?

这是我的代码:

struct DailyData: Identifiable {
    let id = UUID()
    let name: String
    let model: String
    let text: String
}

extension DailyData {
    static func all() -> [DailyData] {
        return [
            DailyData(name: "Beginning", model: "", text: ""),
            DailyData(name: "Midnight Time", model: "Matins", text: ""),
            DailyData(name: "Morning Time", model: "Lauds", text: ""),
            DailyData(name: "Sunrise Time", model: "Prime", text: ""),
            DailyData(name: "Third Hour", model: "Terce", text: ""),
            DailyData(name: "Sixth Hour", model: "Sext", text: ""),
            DailyData(name: "Ninth Hour", model: "None", text: ""),
            DailyData(name: "Evening Time", model: "Vespers", text: ""),
            DailyData(name: "Peace Time", model: "", text: ""),
            DailyData(name: "Night Time", model: "Compline", text: ""),
        ]
    }
}

Firebase 调用:

struct LiturgyData: Codable, Identifiable {
    var id: Int
    var title: String
    var data: String
    
}
public class LiturgyFetcher: ObservableObject {

   @Published var sermons = [LiturgyData]()

    init(){
        load()
    }

    func load() {
        let url = URL(string: "https://MYPRIVATEURL.firebaseio.com/liturgyOfHours/.json")!

        URLSession.shared.dataTask(with: url) {(data,response,error) in
            do {
                if let d = data {
                    let decodedLists = try JSONDecoder().decode([LiturgyData].self, from: d)
                    DispatchQueue.main.async {
                        print("finished getting services")
                        self.sermons = decodedLists
                    }
                }else {
                    print("No Data")
                }
            } catch {
                print ("Error")
            }

        }.resume()

    }
} 

JSON URL 的结果:

[
    {
        "data": "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.",
        "id": 0,
        "title": "Beginning"
    },
    {
        "data": "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.",
        "id": 2,
        "title": "Morning Time (Lauds)"
    }
     
]

看法:

struct DailyWorshipView: View {
    @State private var model = DailyData.all()

    var body: some View {
        NavigationView {
            List {
                ForEach(model) { dailydata in

                    LiturgyCell(dailydata: dailydata)
                }
            }
            .navigationBarTitle(Text("Hours"))
        }
    }

    #if DEBUG
    struct DailyWorshipView_Previews: PreviewProvider {
        static var previews: some View {
            DailyWorshipView()
        }
    }
    #endif
    struct LiturgyCell: View {
        let dailydata: DailyData

        var body: some View {
            NavigationLink(destination: LiturgyDetail(liturgy: dailydata)) {
                HStack {
                    Text(dailydata.name)
                }
            }
        }
    }
}

您没有提供足够的信息,但是,我认为这可能会对您有所帮助。

首先,您需要将LiturgyFetcher添加到DailyWorshipView

@ObservedObject var liturgyFetcher = LiturgyFetcher()

然后你需要一种方法来加入DailyDataLiturgyData

struct DailyData: Identifiable {
    let id = UUID()
    let name: String
    let model: String
    let text: String
    
    // this is just the idea...
    var title: String {
        !model.isEmpty ? "\(name) (\(model))" : name
    }
}

并过滤liturgyFetcher.sermons变量以找到您的礼仪:

liturgyFetcher.sermons.first{ $0.title == dailydata.title }

您的DailyWorshipView可能如下所示(您可能希望将过滤移至LiturgyFetcher ):

struct DailyWorshipView: View {
    @State private var model = DailyData.all()
    @ObservedObject var liturgyFetcher = LiturgyFetcher()

    var body: some View {
        NavigationView {
            List {
                ForEach(model) { dailydata in
                    self.liturgyCell(dailydata: dailydata)
                }
            }
            .navigationBarTitle(Text("Hours"))
        }
    }
    
    func liturgyCell(dailydata: DailyData) -> some View {
        NavigationLink(destination: LiturgyDetail(liturgy: liturgyFetcher.sermons.first{ $0.title == dailydata.title })) {
            HStack {
                Text(dailydata.name)
            }
        }
    }
}

然后,您可以根据需要在LiturgyDetail视图中使用LiturgyData

struct LiturgyDetail: View {
    let liturgy: LiturgyData?

    var body: some View {
        Text("\(liturgy?.title ?? "no liturgy found")")
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM