UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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 Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

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

Reply to this topic…

You need to create an account or log in to reply.

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.