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

Day 60 - confused how to move to another DetailView

Forums > 100 Days of SwiftUI

Hi, I've gotten confused how to organize data. Firstly I've organized users in Response struct, then I saw that maybee it should be inside class to be available everywhere in the app.

Do I initialize with

@ObservedObject var session: Session
or
@ObservedObject var session = Session()

How to move to another friend DetailView from DetailView. What should I pass? There's a Friend struct, But how to move with data of Friend struct into the corresponding User struct?

NavigationLink(destination: DetailView(user:  ???)) {
...
}
class Session: ObservableObject, Codable {
    @Published var users = [User]()
}

struct Response: Codable {
    var users: [User]
}

struct User: Codable {
    var id: String
    var isActive: Bool
    var name: String
    var age: Int16
    var company, email, address, about: String
    var registered: Date
    var tags: [String]
    var friends: [Friend]
}

struct Friend: Codable {
    var id: String
    var name: String
}
struct ContentView: View {
    @State private var users = [User]()
    @ObservedObject var session: Session

    var body: some View {
        NavigationView {
            VStack {
                List(users, id: \.self.id) { user in
                    NavigationLink(destination: DetailView(user: user)) {
                        VStack {
                            HStack {
                                Circle()
                                    .frame(width: 80, height: 80)
                                    .foregroundColor(.gray)
                                    .padding(.trailing)

                                Text(user.name)

                                Spacer()
                            }
                        }
                    }
                }

            }.onAppear(perform: loadData)
            .navigationBarTitle(Text("Friends"))
        }
    }

    func loadData() {
        guard let url = URL(string: "https://www.hackingwithswift.com/samples/friendface.json") else {
            print("Invalid URL")
            return
        }

        let request = URLRequest(url: url)
        URLSession.shared.dataTask(with: request) { data, response, error in
            if let data = data {
                do {

                    let decoder = JSONDecoder()
                    decoder.dateDecodingStrategy = .iso8601
                    let users = try decoder.decode([User].self, from: data)
                    // we have good data - go back to the main thread
                    DispatchQueue.main.async {
                        // update our UI
                        //print(users)
                        self.users = users
                    }

                    // everything is good, so we can exit
                    return
                } catch {
                    print(error)
                }
            }

            // if we're still here it means there was a problem
            print("Fetch failed: \(error?.localizedDescription ?? "Unknown error")")
        }.resume()
    }
}
struct DetailView: View {
    var user: User
    var session: Session

    private var dateFormatter: DateFormatter {
        let df = DateFormatter()
        df.dateStyle = .long
        return df
    }

    var body: some View {
        ScrollView {

            VStack(alignment: .leading, spacing: 10) {
                HStack {
                    Text("\(user.name)")
                    Text(user.isActive ? "🟢" : "⚪️")
                        .font(.caption2)
                }

                Text(user.about)

                ScrollView(.horizontal, showsIndicators: false) {
                    LazyHGrid(rows: [GridItem(.fixed(0))], content: {
                        ForEach(user.tags, id: \.self) { tag in

                            Text(tag)
                                .padding(5)
                                .background(Color.blue.cornerRadius(8))
                                .shadow(radius: 1)
                                .padding(.vertical,40)
                        }
                    })
                }.frame(maxHeight: .infinity)

                Text("Friends")
                    .font(.title)
                    .foregroundColor(.gray)
                    .padding(.top, 10)

                ForEach(user.friends, id: \.self.id) { friend in
                    NavigationLink(destination: DetailView(user:  ???)) {
                        HStack {
                            Image(systemName: "person.crop.circle")
                                .resizable()
                                .frame(width: 32, height: 32)
                            Text(friend.name)
                        }
                    }
                }

            }.padding()

        }
    }
}

3      

It has been a while ago since I wrote this. I remember i was struggling for those navigation links too...

Here is my code and demo. Hope it helps.

3      

Is the friendface JSON file working for you? I'm not able to download it in the simulator. Works fine in Safari, but can't use it in the app.

3      

@slushman
Feb '21 Is the friendface JSON file working for you? I'm not able to download it in the simulator. Works fine in Safari, but can't use it in the app.

I was having trouble with this too. I kept getting the "Fetch failed: Unknown error" error and it ended up being because my field names were not matching the JSON.

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.