NEW: Learn to build amazing SwiftUI apps for macOS with my new book! >>

SOLVED: Sending and Receiving Codable data with URLSession and SwiftUI

Forums > 100 Days of SwiftUI

I followed along with this video but my code didn't work, I had modified the "artist" in the code but I get no responce from doing build and run. No error no timeout nothing. I pasted the url into Safari and it worked got a file with tons of metadata along with it. Apparently I typed something wrong but I can't seem to see it..

import SwiftUI

struct Responce: Codable {
    var results: [Result]
}
struct Result: Codable {
    var trackID: Int
    var trackName: String
    var collectionName: String
}

struct ContentView: View {
    @State private var results = [Result]()

    var body: some View {
        List(results, id: \.trackID) { item in
            VStack(alignment: .leading) {
                Text(item.trackName)
                    .font(.headline)
                Text(item.collectionName)
            }
        }
        .task {
        await loadData()
        }
    }
    func loadData() async {
        guard let url = URL(string:
            "https://itunes.apple.com/search?term=keith+urban&entity=song") else {
            print("Invalid URL")
            return
        }
        do {
            let(data, _) = try await URLSession.shared.data(from: url)
            if let decodedResponce = try? JSONDecoder().decode(Responce.self, from: data) {
                results = decodedResponce.results
            }
        } catch {
            print("Invalid data")
        }
    }
}

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

1      

Went looking thru runtime errors and found a Memory Issues - (1 leaked type) 1 32-byte malloc blocked leaked ! 0x6000003af8ae0

now someone explain that issue....🤪

1      

You get no error because of this:

if let decodedResponce = try? JSONDecoder().decode(Responce.self, from: data) {
    results = decodedResponce.results
}

try? returns an Optional and converts any error into nil, which means you won't know what that error is.

Do this instead:

let decodedResponce = try JSONDecoder().decode(Responce.self, from: data) {
results = decodedResponce.results

And then in the catch clause, print(error) instead of the unhelpful print("Invalid data")

BTW, this:

guard let url = URL(string:
    "https://itunes.apple.com/search?term=keith+urban&entity=song") else {
    print("Invalid URL")
    return
}

is pretty pointless. It will never be nil. You can just do:

let url = URL(string:
    "https://itunes.apple.com/search?term=keith+urban&entity=song")!

The unwrap is safe because the only reason URL.init(string:) would return nil is if you pass it invalid characters. URL doesn't validate anything except that the string is not empty and the characters are valid. Since you are giving it a static string with valid characters, you know with 100% certainty that is not the case.

You only need to use the guard form if you are constructing the URL from user-supplied data that you can't guarantee will be valid.

1      

I get a Circular reference error when I try :

let decodedResponce = try JSONDecoder().decode(Responce.self, from: data) {
results = decodedResponce.results
}
        } catch {
            print(error)
        }

1      

Sorry, I accidentally left a closing brace when I copied from your original post. It should be:

let decodedResponce = try JSONDecoder().decode(Responce.self, from: data)  //no { here
results = decodedResponce.results

1      

That did the trick, once the print(error) was enabled it showed me I had "fat fingered" the .trackId as .trackID so the decoded data threw a error on my typo.... I knew I screwed up somewhere but didn't notice it until the error code was shown. Thanks for the assist!!

1      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Spend less time managing in-app purchase infrastructure so you can focus on building your app. RevenueCat gives everything you need to easily implement, manage, and analyze in-app purchases and subscriptions without managing servers or writing backend code.

Get Started

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.