I've been trying to figure this out before posting and still hitting a wall.
Created an API specific class, a ViewModel, and a View and trying to shuttle data back and forth and while I see the API call is successful and I decode it without issue on logs, it never reflects on the UI or View.
As far as I see I appear to be trying to access the data before it's actually available. All help greatly appreciated!
API Class:
import Combineimport Foundationclass CrunchbaseApi:ObservableObject{ @Published var companies:[Company] = [Company]() @Published var singleCompany:Company? func retrieve(company:String) async { let SingleEntityURL:URL = URL(string:"https://api.crunchbase.com/api/v4/entities/organizations/\(company)?card_ids=fields&user_key=**********REMOVED FOR SECURITY*****************")! let task = URLSession.shared.dataTask(with:SingleEntityURL){ data, response, error in let decoder = JSONDecoder() if let data = data{ do { self.singleCompany = try decoder.decode(Company.self, from: data) } catch { print(error.localizedDescription) } } } task.resume() } func retrieveCompanyList() { //declare }}
ViewModel:
import Combineimport Foundationclass CompanyViewModel: ObservableObject{ var crunchbase:CrunchbaseApi = CrunchbaseApi() @Published var singleCompany:Company? func retrieveCompany(company:String) async { await self.crunchbase.retrieve(company: company) self.singleCompany = crunchbase.singleCompany }}
View:
import SwiftUIstruct CompanyView: View{ @State var companyViewModel:CompanyViewModel = CompanyViewModel() var body: some View { NavigationView { VStack { Text("Company ID: \(companyViewModel.singleCompany?.id ?? "NOTHING")") // Text("Company Name: \(companyViewModel.companyName)") // Text("Company Summary: \(companyViewModel.companyDescription)") // Text("Logo URL: \(companyViewModel.companyLogoURL)") }.navigationTitle("Company") } }}