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

Decoding json

Forums > SwiftUI

I want to make a call to https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY

and then decode the result into a structure.

The result does not come back as an array, and I'm having problems.

Can someone help me with some basic code to get the data into a structure? Thanks

3      

Hey there - can you provide a snippet of the JSON response? Does it come back as a Dict instead of array?

3      

sorry, I've updated the api call to include the demo key. if you try the link again it will work now

3      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

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

Ah I see now - so instead of creating a var that points to another struct as an array, I believe you could just setup a struct pointing to the different string objects within the dict, like so:

struct NASAData: Codable, Identifiable {
    let id = UUID()
    var copyright: String
   var date: String
   var explanation: String
   var hdurl: String
   var media_type: String
   var service_version String
   var title: String
   var url: String
}

Then somewhere in your class that actually retrieves and publishes the API results, you'd have something like this:

let fetch = try! JSONDecoder().decode(NASAData.self, from: data)

This is a great tutorial/primer on fetching via API and should visualize it better: https://www.youtube.com/watch?v=1en4JyW3XSI

3      

That's great help, many thanks.

4      

So I now have this code, sorry formatting seems screwed up.

import SwiftUI

struct NASAData: Codable, Identifiable { let id = UUID() var copyright: String? var date: String var explanation: String var hdurl: String var media_type: String var service_version: String var title: String var url: String

}

class Api { func getPosts(completion: @escaping (NASAData) -> ()) { guard let url = URL(string: "https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY") else { return }

    URLSession.shared.dataTask(with: url) { (data, _, _) in
        let posts = try! JSONDecoder().decode(NASAData.self, from: data!)

        DispatchQueue.main.async {
            completion(posts)
        }
    }
.resume()
}

}

but I am still unsure what to put into ContentView.swift to make the call and display the results.

3      

First of all, you need to learn to build a simple Url session...😱

3      

You can't ignore Error here

and

also unsafe unwrapping is just brave

but not for good coding...

3      

thanks DimNovo, i have stripped out all the error checking stuff as that is not relavent to the issue.

3      

thanks DimNovo, i have stripped out all the error checking stuff as that is not relavent to the issue.

🙂

3      

https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY

This link may be blocked for a short time - use your private API key...

3      

i have a private key, but i did not want to post it here. i put the demo key in the code, so anyone can try it out to see what is returned.

3      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

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.