In my app, the user can search for an image from a specific API and then click on a button to get that image's url. My question is how to display the image to the user?
ContentView:
The function in DataModel() that fetches the data:
Now, how can I display the image after the user presses on the Button?
ContentView:
Code Block @StateObject var dataModel = DataModel() var body: some View { // Text to display the link of the Image, when clicked on, it opens in Safari: Text("\(dataModel.imageURL)") .padding() .onTapGesture { let url = URL(string: dataModel.imageURL) guard let recievedURL = url, UIApplication.shared.canOpenURL(recievedURL) else { return } UIApplication.shared.open(recievedURL) } // TextField where the user enters the search word: TextField("Search Images...", text: $dataModel.searchTerm) // After pressing this button, the DataModel fetches the data and presents the url in the text above: Button(action: { dataModel.fetchAPI() }, label: { Text("Fetch Image") }) }
The function in DataModel() that fetches the data:
Code Block @Published var imageURL = String() @Published var searchTerm = String() func fetchAPI() { guard let url = URL(string:{The url including the searchWord}) else { return } URLSession.shared.dataTask(with: url) { (data, response, error) in guard let recievedData = data, error == nil else { print("ERROR: \(String(describing: error?.localizedDescription))") return } do { let model = try JSONDecoder().decode(ImageData.self, from: recievedData) DispatchQueue.main.async { self.imageURL = model.data.first?.url ?? "No URL" } } catch { print("Error: \(error.localizedDescription)") } } .resume() }
Now, how can I display the image after the user presses on the Button?