NEW: My new book Pro SwiftUI is out now – level up your SwiftUI skills today! >>

Day 61 challenge: trouble loading [Friends]

Forums > 100 Days of SwiftUI

I've been stuck at this for hours now and I've tried everything I could think of. I've loaded the JSON data into structs and just want to make the Core Data entities from that (I'm not trying to go directly from JSON to Core Data).

The regular things show up just fine but I can't get the friends (and tags) to work properly no matter what I do.

I've set up a one to many relationship with "CDFriend" and this is my content view right now:

//
//  ContentView.swift
//  FriendFace
//
//

import SwiftUI

struct ContentView: View {

    @Environment(\.managedObjectContext) var moc
    @State var usersAll = [User]()

    @FetchRequest(entity: CDUser.entity(), sortDescriptors:[]) var userCDList: FetchedResults<CDUser>

    var body: some View {
        NavigationView{
//            List(usersAll, id: \.id) { user in
//                NavigationLink(destination:userView(user: user, allUsers: usersAll)){
//                    Text(user.name)
//                }
//            }.navigationBarTitle("FriendFace")
//            .onAppear(perform: loadData)

            List(userCDList, id: \.id) { user in
                            NavigationLink(destination:userView(user: user, allUsers: usersAll)){
                                Text(user.wrappedName)

                            }
                        }.navigationBarTitle("FriendFace")
                        .onAppear(perform: loadData)
        }
    }

    func buildCD(){

        for user in usersAll {

            let newUser = CDUser(context: self.moc)

            newUser.name = user.name
            newUser.id = user.id
            newUser.isActive = user.isActive
            newUser.age = Int16(user.age)
            newUser.company = user.company
            newUser.email = user.email
            newUser.address = user.address
            newUser.about = user.about
            newUser.registered = user.registered
            newUser.tags = ""

            var tempFriendsArray = Array<CDFriend>()

            for friend in user.friends{

                let newFriend = CDFriend(context: moc)
                newFriend.name = friend.name
                newFriend.id = friend.id

                tempFriendsArray.append(newFriend)

            }

            newUser.friends = NSSet(array: tempFriendsArray)

            try? self.moc.save()

        }
    }

    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{

                if let decodedResponse = try? JSONDecoder().decode([User].self, from: data){

                    DispatchQueue.main.async {
                        self.usersAll = decodedResponse
                        buildCD()
                    }

                    return

                }
            }

            print("Fetch failed: \(error?.localizedDescription ?? "Unknown error")")

        }.resume()

    }

}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

I also tried using this:

 newUser.addToFriends(newFriend)

instead of making a temporary array but this didnt work either.

I'd really appreciate any help!

I'm really on the verge of giving up on this challenge...

1      

I don't know wether I am right,but I think " newUser.friends = NSSet(array: tempFriendsArray)" this will not be saved correctly.Its type is arrary,which can't be saved correctly, the type of tags is also array,so there are songthing wrong.

1      

Hacking with Swift is sponsored by Play

SPONSORED Play is the first native iOS design tool created for designers and engineers. You can install Play for iOS and iPad today and sign up to check out the Beta of our macOS app with SwiftUI code export. We're also hiring engineers!

Click to learn more about Play!

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.