How to fetch Google Places data in SwiftUI?

Viewed 152

I'm new to SwiftUI. Currently struggling with fetching and presenting photos and places names to my List from Google Places (Maps) API. I do know that they provide explanation of how to do it, but since I'm not that experienced yet, i cannot get the code provided just for Swift (not Swift UI). Tried to use the method below:

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

struct Place: Codable {
    var placeId: Int
    var placeName: String
    var placePic: String
    var placeTime: String
    var placePhone: String
    var placeLocation: String
}
  
  
    @State var results = [Place] ()

    var body: some View {

        List(results, id: \.placeId) { item in
            VStack{
                Text(item.placeName)
            }
        }.onAppear(perform: loadData)
    }
    func loadData(){
        guard let url = URL(string: "https://maps.googleapis.com/maps/api/place/photo?parameters") else{

            print("Invalid URL")

            return
        }
        let request = URLRequest(url: url)

        URLSession.shared.dataTask(with: request){data, responce, 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 ?? "Unknown  error")")

        }.resume()
    }
}

Question:

Is there any ideas of what i do wrong? Because I tried to search for some tutorials on the web, using SwiftUI, but haven't found any.

0 Answers
Related