Hi there! I'm new with iOS development so I know that my question is quite easy for you guys. It would be great is you could help me to keep moving forward. I'm trying to request data from an API when a view appears. Here is my code:
The problem is when I do in the body
Thank you
Dennis
Code Block swift import SwiftUI // Define data structure for API function struct DescriptionResponse: Codable { var results: [DescriptionResult] } struct DescriptionResult: Codable { var id: String var symbol: String var cik: Int var name: String var sic: Int var sector: String var location: String var mailing_address: String var business_address: String var business_latitude: Float var business_longitude: Float } struct DescriptionScreen: View { var selectedCik: Int @State var descriptionResults = [DescriptionResult]() // define State variable for API Function var body: some View { ZStack { Color("CustomBackground") .edgesIgnoringSafeArea(.all) VStack { Maps(Lat: 34, Long: -116, LatSpan: 2, LongSpan: 2).cornerRadius(20) .edgesIgnoringSafeArea(.all) HStack { RoundedRectangle(cornerRadius: 20) .shadow(color: Color.gray.opacity(0.2), radius: 5) .foregroundColor(.white) .padding() .overlay(Text("SYMBOL") .font(.title) .fontWeight(.semibold)) RoundedRectangle(cornerRadius: 20) // Spacer() is not working .foregroundColor(Color("CustomBackground")) } .frame(height: 100.0) RoundedRectangle(cornerRadius: 20) .padding() .foregroundColor(.white) .shadow(color: Color.gray.opacity(0.2), radius: 5) .overlay( Text("DESCRIPTION") .multilineTextAlignment(.leading) .padding(.all, 30.0) , alignment: .top ) } }.onAppear { self.descriptionRequest(url: "myURL") } } // Define function API Request func descriptionRequest(url: String) { // First replace spaces for & in the parameter (searchText) let urlEncode = url.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? url guard let url = URL(string: urlEncode) else { print("Invalid URL") return } let request = URLRequest(url: url) URLSession.shared.dataTask(with: request) { data, reponse, error in if let data = data { if let decodedResponse = try? JSONDecoder().decode(DescriptionResponse.self, from: data) { DispatchQueue.main.async { self.descriptionResults = decodedResponse.results } return } } print("Fetch failed: \(error?.localizedDescription ?? "Unknown error")") }.resume() } }
The problem is when I do in the body
Code Block Text(descriptionResults[0].symbol)
I get an error because the array is empty. If I put a Code Block print
statement before the Code Block return
of the function, It prints the array correctly. What am I missing? Thank you
Dennis