简体   繁体   中英

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

I am trying to retrieve data from my firebase realtime database but I am stuck on the following code how to approach it properly. I have a tableview list of categories where when the select of the certain category, I want to show that particular data which is data key value from database onto the view. Is it possible?

Here is my code:

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 call:

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 Result from 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)"
    }
     
]

View:

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

You didn't provide enough information, however, I think this might help you.

First, you need to add LiturgyFetcher to your DailyWorshipView :

@ObservedObject var liturgyFetcher = LiturgyFetcher()

Then you need a way to join DailyData with LiturgyData :

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
    }
}

and filter liturgyFetcher.sermons variable to find your liturgy:

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

Your DailyWorshipView may look like this (you may want to move filtering to the 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)
            }
        }
    }
}

Then you can use LiturgyData in your LiturgyDetail view as desired:

struct LiturgyDetail: View {
    let liturgy: LiturgyData?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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