【问题标题】:How to retrieve data from firebase properly with a url in Swift?如何使用 Swift 中的 url 从 firebase 正确检索数据?
【发布时间】:2020-06-25 17:15:17
【问题描述】:

我正在尝试从我的 firebase 实时数据库中检索数据,但我被以下代码困住了如何正确处理它。我有一个表查看的类别列表,在某些类别选择某个类别时,我想向@ 987654321从数据库显示到视图中的@ 987654321键值。有可能吗?

这是我的代码:

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()

    }
} 

来自 URL 的 JSON 结果:

[
    {
        "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)
                }
            }
        }
    }
}

【问题讨论】:

  • 您面临的实际问题是什么?
  • 当我选择类别以将数据键值显示到我的视图时,未获取键值“数据”。
  • 你能把你的view的代码也加进去吗?
  • 我添加了视图
  • 您在哪里以及如何将您的类别与下载的数据合并?

标签: ios swift firebase firebase-realtime-database swiftui


【解决方案1】:

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

首先,您需要将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")")
    }
}

【讨论】:

  • liturgyFetcher.sermons.first{ $0.title == dailydata.title } 将进入 json 调用,对吗?
  • @Vince 目前在我的代码中是DailyWorshipView。您可能希望在 LiturgyFetcher 中添加另一种方法来获取特定的 LiturgyData,但它也适用于当前代码。看看我的DailyWorshipView 版本——你提到的代码在 NavigationLink 中。
  • 谢谢。我会尽快测试你的代码并让你知道它是否有效。谢谢!
  • 另外,它有效。但是如果文本很长,如何使视图可滚动?
  • @Vince 如果这个问题得到回答,请添加另一个问题。我很乐意为您提供帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-22
  • 2017-10-15
  • 2016-08-12
相关资源
最近更新 更多