简体   繁体   English

使用 Codable 解码 JSON,然后填充我的 SwiftUI

[英]Decode JSON using Codable and then populate my SwiftUI

I am new to Swift and SwiftUI.我是 Swift 和 SwiftUI 的新手。 I am currently teaching myself how to code (loving it!) through hackingwithswift.com I am currently on Day 60 and I am stuck and not sure what to do from here.我目前正在通过 hackingwithswift.com 自学如何编码(喜欢它!)我目前在第 60 天,我被困住了,不知道从这里开始做什么。

The challenge is to decode some information using Codable and populate SwiftUI.挑战是使用 Codable 解码一些信息并填充 SwiftUI。

I created a struct to match the JSON, but when I go to run the app, I keep getting my error "Fetch Failed: Unknown Error" and therefore my UI won't update.我创建了一个结构来匹配 JSON,但是当我去运行应用程序时,我不断收到错误“获取失败:未知错误”,因此我的 UI 不会更新。

Would someone glance at my code and provide any pointers on where I am going wrong and possibly why?有人会看一下我的代码并提供有关我出错的地方以及可能的原因的任何指示吗? Thank you so much for any suggestions and help, it is much appreciated!非常感谢您的任何建议和帮助,非常感谢! Code is posted below.代码贴在下面。

Cody科迪

import SwiftUI

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

struct User: Codable, Identifiable {
    let id: String
    let isActive: Bool
    let name: String
    let age: Int
    let company: String
    let email: String
    let address: String
    let about: String
    let registered: String
    let tags: [String]
    
    struct FriendRole: Codable {
        let id: String
        let name: String
    }
    
    let friend: [FriendRole]
    
}

struct ContentView: View {
    @State private var results = [User]()
    
    var body: some View {
        List(results, id: \.id) { item in
            VStack(alignment: .leading) {
                Text(item.name)
                    .font(.headline)
                Text(item.address)
            }
        }
    .onAppear(perform: loadData)
    }
    
    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(Response.self, from: data) {
                    DispatchQueue.main.async {
                        self.results = decodedResponse.results
                    }
                    return
                }
            }
            print("Fetch Failed: \(error?.localizedDescription ?? "Unkown Error").")
        }.resume()
    }
}

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

I'm also new to swiftUI this is how I managed to make it work by using Observable Objects我也是 swiftUI 的新手,这就是我如何通过使用 Observable Objects 使其工作

Here's the structures Since in the json file there is a [ in the very beginning you do not have to create a struct that has a User array you could create a struct and then create a variable of that struct type as an array这是结构因为在 json 文件中有一个 [ 在一开始你不必创建一个具有用户数组的结构你可以创建一个结构然后创建一个该结构类型的变量作为一个数组

here's how I did it这是我如何做到的

I created separate files for instance for the structures i had a different file for them例如,我为结构创建了单独的文件,我为它们创建了不同的文件

here's what I have for my structure file这是我的结构文件

import Foundation



struct User : Codable, Identifiable {
    let id : String
    let isActive : Bool
    let name : String
    let age : Int
    let company : String
    let email : String
    let address : String
    let about : String
    let registered : String
    let tags = [String]()
    let friends = [Friends]()
}


struct Friends : Codable {
    let id : String
    let name : String
}

I created another file for the observable object class我为 observable 对象类创建了另一个文件

class JsonChannel : ObservableObject {
    @Published var retVal = [User]()
    func getInfo () {
        guard let url = URL(string: "https://www.hackingwithswift.com/samples/friendface.json") else {return}
        URLSession.shared.dataTask(with: url) { (data, resp, err) in
            if let data = data {
                DispatchQueue.main.async {
                    do {
                        self.retVal = try JSONDecoder().decode([User].self, from: data)
                    }
                    catch {
                        print(error)
                    }
                }
            }
        }.resume()
    }
}

and here's what i have for my contentView file这是我的 contentView 文件

import SwiftUI

struct ContentView : View {
    @ObservedObject var info = JsonChannel()
    var body: some View {
        VStack {
            Button(action: {
                self.info.getInfo()
            }) {
                Text("click here to get info")
            }
            List {
                ForEach (self.info.retVal) { item in
                    VStack {
                        Text("\(item.name)")
                        Text("\(item.address)")
                    }
                    
                }
            }
        }
    }
}

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

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM