1

I have problem with showing JSON Data in SwiftUI, I get the data from Genius API I currently search for song and can confirm that I get the data extracted correctly; example I can print out the title of the result:

enter image description here

This is how I fetch the data

class NetworkManager: ObservableObject {
    var objectWillChange = PassthroughSubject<NetworkManager, Never>()

    var fetchedSongsResults = [hits]() {
        willSet {
            objectWillChange.send(self)
        }
    }

    init() {
        fetchSongs()
    }

    func fetchSongs() {
        guard let url = URL(string: "https://api.genius.com/search?q=Sia") else { return }
        var urlRequest = URLRequest(url: url)
        urlRequest.setValue("Bearer TOKEN", forHTTPHeaderField: "Authorization")

      URLSession.shared.dataTask(with: urlRequest) {data, response, error in
            guard let data = data else { return }
            //print(String(decoding: data, as: UTF8.self))
            let songs = try! JSONDecoder().decode(feed.self, from: data)
            DispatchQueue.main.async {
                self.fetchedSongsResults = songs.response.hits

            }
        }.resume()
    }
}

So when I get the data I save to the variable fetchedSongsResults and this seems correctly but for what ever reason when I try to print the count for example it says that i empty and also I can't loop through the fetchedSongsResults using a list or ForEach this is how, (which I believe s because I have not made the model identifiable) I tried to print the count of fetchedSongsResults,

This initialized outside the body (just so you know)

@State var networkManager = NetworkManager()

This is inside the body

Text("\(networkManager.fetchedSongsResults.count)")

If your are wondering how my structure looks like when I decode the JSON Data then here it is

struct feed: Codable {
   var meta: meta
   var response: response
}

struct meta: Codable {
   var status: Int
}

struct response: Codable {
   var hits: [hits]
}

struct hits: Codable {
   var index: String
   var type: String
   var result: song
}

struct song: Codable, Identifiable {
   var id: Int
   var header_image_thumbnail_url: String
   var url: String
   var title: String
   var lyrics_state: String
   var primary_artist: artist

}

struct artist: Codable {
   var name: String
}
3
  • @State for NetworkManager looks wrong since this means the networkManager is somehow is tied to a user interface component which I suppose it isn't. Commented Nov 15, 2019 at 18:51
  • If the value in your Authorization header is private, you might want to remove it from your question. Commented Nov 15, 2019 at 20:14
  • Yes you are right and @ObservedObject solved the problem but I wanted to ask do you know why I cannot use in a list get the following error "Cannot convert value of type '() -> ()' to expected argument type '() -> _'" Commented Nov 15, 2019 at 20:18

1 Answer 1

1

Try: @ObservedObject var networkManager = NetworkManager().

Sign up to request clarification or add additional context in comments.

3 Comments

Yes it actually worked however I have another problem is that is I cannot use this with a list I get the following error "Cannot convert value of type '() -> ()' to expected argument type '() -> _'"
your struct value is empty, try put some preset value to check whether this problem still exist
I tried you solution and it didn't work but thanks anyway

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.