'How can I declare the Json variable in this case on swiftUI
It cannot show the result, anyone knows?
struct Course: Hashable, Codable {
let id:String
let display:String
}
class ViewModel: ObservableObject{
@Published var courses: [Course]= []
func fetch(){
guard let url = URL(string:"https://www.i-design.hk/api/menu/userMenuRequest.php?type=userMenu&action=l&userId=200380")else{
return
}
let task = URLSession.shared.dataTask(with: url) { [weak self]data,_, error in
guard let data = data, error == nil else {
return
}
I have tried many times to change the code, but I cannot show the JSON string correctly. Anyone can help me?
Solution 1:[1]
when the response came from API it came in form of JSON and you need to decode that JSON so that can easily read by swift, so you should decode the response like that and when you get the response you should assign the data to the courses variable so that it will published to the view
struct Course: Hashable, Codable {
let id:String
let display:String
}
class ViewModel: ObservableObject{
@Published var courses: [Course]= []
@Published var error: String = ""
func fetch(){
guard let url = URL(string:"https://www.i-
design.hk/api/menu/userMenuRequest.php?
type=userMenu&action=l&userId=200380")else{
return
}
let task = URLSession.shared.dataTask(with: url) { [weak
self]data,_, error in
guard let data = data, error == nil else {
return
}
do{
let ResponseResult = try JSONDecoder().decode([Course], from: data)
courses = ResponseResult
}catch(let error){
error = error.localizedDescription
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | belal medhat |
