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

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()
    }
}

2      

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....🤪

2      

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.

2      

I get a Circular reference error when I try :

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

2      

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

2      

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!!

2      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

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.