Home > Blockchain >  I tried to make a simple HTTP request in SwiftUI but when I assign value to Published Variable I got
I tried to make a simple HTTP request in SwiftUI but when I assign value to Published Variable I got

Time:08-18

Here's the code

import Combine
import Foundation


struct Cate: Hashable, Codable {
    var name: String
    var property: String
}

final class CatesDataModel: ObservableObject {
    
    @Published var cates_list = [Cate]()
    @Published var grouped_cates = [GroupedCates]()
    
    
   init() {
        fetchCates(user_id: "X45045")
   }
    
    func fetchCates(user_id: String) {
        
        
        
        let url = URL(string: API_URL)!
        var request = URLRequest(url: url)
        request.httpMethod = "GET"
        

        URLSession.shared.dataTask(with: request) { [weak self] data, response, error in
            
            DispatchQueue.main.async {
                if error != nil || (response as! HTTPURLResponse).statusCode != 200 {
                    
                } else if let data = data {
                    
                    do {
                       
                        let response = try JSONDecoder().decode(fetchCatesResponse.self, from: data)
                        
                        let grouped_dict = Dictionary(grouping: response.data, by: { $0.property })
                        
                        if response.status == "success" {
                            self?.cates_list = response.data
                          
                            
                        }
                    } catch {
                        print(error)
                    }
                    
                }
            }
            
        }.resume()
        
    }
    
}

fileprivate struct fetchCatesResponse: Decodable {

    // MARK: - Properties
    
    let status: String
    let data: [Cate]

}

I don't know where is wrong, when I execute print(response.data), its value showed correctly, but when I execute print(self?.cates_list), it got nil? I'm new to SwiftUI from Python Backend, maybe the question is too simple but I cannot deal with it on my own, hope someone can tell me where is wrong.

CodePudding user response:

EDIT-1:

try this example code:

// for testing
struct GroupedCates: Hashable, Codable {
    var groupName: String
}

struct Cate: Hashable, Codable {
    var name: String
    var property: String
}

fileprivate struct CatesResponse: Decodable {
    let status: String
    let data: [Cate]
}

final class CatesDataModel: ObservableObject {
    @Published var cates_list = [Cate]()
    @Published var grouped_cates = [GroupedCates]()

   init() {
        fetchCates(user_id: "X45045")
   }
    
    func fetchCates(user_id: String) {
        let url = URL(string: "API_URL")!
        var request = URLRequest(url: url)
        request.httpMethod = "GET"
        URLSession.shared.dataTask(with: request) { data, response, error in
            DispatchQueue.main.async {
                if error != nil || (response as! HTTPURLResponse).statusCode != 200 {
                    print(error)
                }
                else if let data = data {
                    print(String(data: data, encoding: .utf8)) // <-- here
                    do {
                        // -- here
                        let decodedResponse = try JSONDecoder().decode(CatesResponse.self, from: data)
                        if decodedResponse.status == "success" {
                            self.cates_list = decodedResponse.data  // <-- here
                            print("\n---> self.cates_list: \(self.cates_list)")
                        }
                    } catch {
                        print(error)
                    }
                }
            }
        }.resume()
    }
    
}
  • Related