0

This may be a noob question, but I am trying to make an API call with the trakt.tv API. However, no data is showing up, and I am unsure why this is occurring. This is my view code:

import SwiftUI

struct ContentView: View {
    
    @State private var trendingMovies = [TrendingMovie]()
    
    var body: some View {
        NavigationView {
            List(trendingMovies, id: \.movie.ids.tmdb ) { trendingMovie in
                VStack {
                    Text(trendingMovie.movie.title)
                    Text("\(trendingMovie.movie.year)")
                }
            }
            .navigationTitle("Hello")
            .task {
                await fetchTrendingMovies()
            }
        }
    }
    
    func fetchTrendingMovies() async {
        
        guard let url = URL(string: "https://api.trakt.tv/movies/trending") else {
            print("Could not get trending movies.")
            return
        }
        
        do {
            let (data, _) = try await URLSession.shared.data(from: url)
            
            if let decodedResponse = try? JSONDecoder().decode([TrendingMovie].self, from: data) {
                print("We got the trending movies.")
                trendingMovies = decodedResponse
            }
        } catch {
            print("Could not get trending movies.")
        }
    }
}

This is my model code:

struct TrendingMovie: Codable {
    let watchers: Int
    let movie: Movie
}

struct Movie: Codable {
    let title: String
    let year: Int
    let ids: IDS
}

struct IDS: Codable {
    let trakt: Int
    let slug: String
    let imdb: String
    let tmdb: Int
}

I am still new to this stuff, so any help would be greatly appreciated. This is the first time I am working with an API on my own.

MohAliBou
  • 61
  • 6
  • Remove the try? When parsing. What does the print(…) says? – CloudBalancing May 29 '22 at 23:04
  • By using `try?` instead of do/try/catch, your throwing away any chance of seeing an error – jnpdx May 29 '22 at 23:04
  • @CloudBalancing Removing the `try?` causes Xcode to give me an error: `Initializer for conditional binding must have Optional type, not '[TrendingMovie]'`. – MohAliBou May 29 '22 at 23:33
  • @jnpdx What would be a better way of going about this? – MohAliBou May 29 '22 at 23:35
  • 1
    Note, the url you use in your code, `https://api.trakt.tv/movies/trending` does not work, i.e it returns nothing when used in a browser. This could be the source of your problem. – workingdog support Ukraine May 29 '22 at 23:35
  • To connect to the server, you have to build a request with the appropriate url, parameters and required headers, including your "trakt-api-key" etc... See the requirements here: https://trakt.docs.apiary.io/#introduction/api-url – workingdog support Ukraine May 30 '22 at 00:05
  • @workingdogsupportUkraine If it's not too much to ask, could you provide an example on how I can do this? I've never seen anyone connect to an API like this before. – MohAliBou May 30 '22 at 00:10
  • there are many examples on SO, and elsewhere using swift with async or combine and/or closures. Do some basic search, try a few things, you will learn a lot more than me providing you with an answer. – workingdog support Ukraine May 30 '22 at 00:17
  • @workingdogsupportUkraine Sounds good. You know any examples on SO where I can start looking? I honestly don't know where to start, as all tutorials I have seen on getting an API have nothing to do with what seems to be required here. – MohAliBou May 30 '22 at 00:26
  • have a look at these to get info on URLRequest: https://stackoverflow.com/questions/68512063/async-request-to-unsplash-api-not-working-correctly https://stackoverflow.com/questions/69552627/problem-making-api-request-with-async-await-in-swift-5-5 https://stackoverflow.com/questions/70692615/displaying-state-of-an-async-api-call-in-swiftui https://stackoverflow.com/questions/71241937/urlrequest-error-the-given-data-was-not-valid-json https://stackoverflow.com/questions/58083255/how-to-display-json-data-from-api-in-swiftui/58084185#58084185 – workingdog support Ukraine May 30 '22 at 00:44
  • There are also a number of swift libraries on github that deal with trakt API. Maybe worth a look. eg: https://github.com/topics/trakt-tv?l=swift – workingdog support Ukraine May 30 '22 at 00:58

0 Answers0