swiftswiftui

How to using the fetched data?


I am currently working on an IOS app, I am trying to design a carousel with the fetched json data. This is how I get the targeted json data.

class loadDate: ObservableObject {
    @Published var todos = [Result]()
    
    init() {
        let url = URL(string: "https://api.themoviedb.org/3/movie/now_playing?api_key=<api_key>&language=en-US&page=1")!
        URLSession.shared.dataTask(with: url) { data, response, error in
            // step 4
            if let data = data {
                if let decodedResponse = try? JSONDecoder().decode(Response.self, from: data) {
                   
                    DispatchQueue.main.async {
                       
                        self.todos = decodedResponse.results
                    }

                    // everything is good, so we can exit
                    return
                }
            }

            
            print("Fetch failed: \(error?.localizedDescription ?? "Unknown error")")
        }.resume()
    }
    
 }

It looks like I can only use the data in a list view, for example,

    struct ContentView: View {
    @ObservedObject var fetch = loadDate()
    var body: some View {
        HStack {
            
            List(fetch.todos) { item in
                HStack {
                    VStack(alignment: .leading) {
                        Text(item.title)
                            .font(.headline)

                        Text(item.poster_path)
    //
                    }
                }

            }
            
        }
        
    }
    
}

Within this list view, I can access all elements like using fetch.todos[0].title. However, if outside the list view, fetch.todos[0].title would fail, can someone give some advice on how to use the data outside the list view .


Solution

  • If todos is an empty array, fetch.todos[0].title will always fail. So whenever you need to access your todos directly you can use something like this

    Group {
        if fetch.todos.count > 0 {
            Text("Title of first todo \(fetch.todos[0].title)")
        } else {
            Text("Todos are empty")
        }
    }