TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

SOLVED: Unable to perform search using iTunes API for FastTrack app

Forums > macOS

I am stuck trying to get my Fast Track app to load any search results. I've enabled the Outgoing Client Connection and as far as I'm aware my code is correct. However, clicking the "search" button returns nothing and I'm convinced the problem is in my view code. If someone is able to spot the error or potentially point me in the right direction that would be much appreciated!

struct ContentView: View {

    let gridItems: [GridItem] = [
        GridItem(.adaptive(minimum: 150, maximum: 200)),
    ]
    @AppStorage("searchText") var searchText = ""
    @State private var tracks = [Track]()

    var body: some View {
        VStack{
            HStack{
                TextField("Search for a song", text: $searchText)
                    .onSubmit(startSearch)
                Button("Search", action: startSearch)
            }
            .padding([.top, .horizontal])

            ScrollView {
                LazyVGrid(columns: gridItems) {
                    ForEach(tracks) { track in
                        AsyncImage(url: track.artworkURL) { image in
                            image.resizable ()
                        } placeholder: {
                            ProgressView()
                        }
                            .frame(width: 150, height: 150)
                    }
                }
            }
        }
    }

    func startSearch() {
        Task {
            try await performSearch()
        }
    }

    //“fetch the iTunes API URL with the user’s search text, download the data, convert it into a SearchResult object, then store its results array somewhere”
    func performSearch() async throws {
        guard let url = URL(string: "https://itunes.apple.com/search?term=\(searchText)&limit=100&entity=song") else {return}
        let (data, _) = try await URLSession.shared.data(from:url)
        let searchResult = try JSONDecoder().decode(SearchResult.self, from: data)
        tracks = searchResult.results
    }
}

    struct ContentView_Previews: PreviewProvider {
        static var previews: some View {
            ContentView()
        }
    }

3      

Hi,

I think the problem is in the url, the (searchText) has white space on it

let text = searchText.lowercased().replacingOccurrences(of: " ", with: "+")
guard let url = URL(string: "https://itunes.apple.com/search?term=\(text)&limit=100&entity=song") else {
    print("Invalid URL")
    return

}

Also try to put a do catch block on your strartSearch method so you know if there is an error decoding.

func startSearch() {
    Task {
        do {
            try await performSearch()
        } catch {
            print(error)
        }
    }
}

3      

Hacking with Swift is sponsored by Superwall.

SPONSORED Superwall lets you build & test paywalls without shipping updates. Run experiments, offer sales, segment users, update locked features and more at the click of button. Best part? It's FREE for up to 250 conversions / mo and the Superwall team builds out 100% custom paywalls – free of charge.

Learn More

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.