TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

Read Json data and read it on ContentView

Forums > SwiftUI

Hello guys, on parsing Json in SwiftUI question:

I parse data from remote Json and give it to output in console. In this step is very good.

How I can "insert" read this data field on my ContentView?.. I'm stuck on this....

Please help! or give me suggest tutorial, where is detailed about this.

Thanks!

I got error

Value of type 'UserResults' has no member 'email'

on Text(ppl?.email ?? "Email Placeholder") string

ContentView file:


import SwiftUI

struct ContentView: View {

    @State private var ppl: UserResults?

    var body: some View {
        VStack {
            Image(systemName: "globe")
                .imageScale(.large)
                .foregroundStyle(.tint)
            Text("Hello, world!")
            Text(ppl?.email ?? "Email Placeholder")
        }
        .onAppear {
            NetworkServiceWithCompletions.shared
                .fetchData { result in
                    switch result {
                    case .success(let usersData):
                        print("Data:\(usersData.results[0].email)")
                    case .failure(let failure):
                        print(failure.localizedDescription)
                    }
              }
        }
        .padding()
    }
}

#Preview {
    ContentView()
}

User file

import Foundation

struct UserResults: Decodable {
    let results: [User]

    struct User: Decodable {
        var gender: String
        var name: Name
        var email: String
        var picture: Picture

        struct Name: Decodable {
            var title: String
            var first: String
            var last: String
        }

        struct Picture: Decodable {
            var large: String

        }

    }

}

NetworkServiceWithCompletions file

import Foundation

class NetworkServiceWithCompletions: ObservableObject {

    static let shared = NetworkServiceWithCompletions(); private init() { }

    private func createURL() -> URL? {
        let tunnel = "https://"
        let server = "randomuser.me"
        let endpoint = "/api"
        let getParams = ""
        let urlStr = tunnel + server + endpoint + getParams

        let url = URL(string: urlStr)
        return url
    }

    func fetchData(completion: @escaping (Result<UserResults, Error>) -> ()) {
        guard let url = createURL() else {
            completion(.failure(NetworkingError.badUrl))
            return
        }

            URLSession.shared.dataTask(with: url) { data, response, error in
                guard let data else {
                    if let error {
                        completion(.failure(error))
                    }
                    return
                    }

                 let decoder = JSONDecoder()
                decoder.keyDecodingStrategy = .convertFromSnakeCase
                do {
                    let usersData = try decoder.decode(UserResults.self, from: data)
                    completion(.success(usersData))
                } catch {
                    completion(.failure(NetworkingError.invalidData))
                }

                }.resume()
            }
        }

    enum NetworkingError: Error {
        case badUrl, badRewuest, badResponse, invalidData
    }

I got error

Value of type 'UserResults' has no member 'email'

on Text(ppl?.email ?? "Email Placeholder") string

2      

Because email is ppl>[results]>email. Try

Text(ppl?.results[0].email ?? "Email Placeholder")

2      

Ok error is gone, but only "Email Placeholder" is showing... not real email string...

2      

That sound like ppl? is still nil

2      

I know about nil, but can I fix this?

Where is my mistake?..

2      

ppl is nil because it is not set anywhere

you can set it inside the case .success:
ppl = usersData

2      

Hacking with Swift is sponsored by Blaze.

SPONSORED Still waiting on your CI build? Speed it up ~3x with Blaze - change one line, pay less, keep your existing GitHub workflows. First 25 HWS readers to use code HACKING at checkout get 50% off the first year. Try it now for free!

Reserve your 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.