-1

This is my Json file and i don't understand how to fetch data and set the Image in our SwiftUI code. please help me resolve this problem.

And this is My Model, is this model correct? This is My API and wants to fetch only value images array

import Foundation


public struct BannerImages {
    public let images: [String]

    public init(images: [String]) {
        self.images = images
    }
}
2
  • 2
    Don't take it the wrong way, but it sounds like what you need is a tutorial or lesson on Swift and SwiftUI. YouTube is full of those, I particularly enjoy this guy youtube.com/c/PaulHudson. I think if you watch a few videos and still can't solve it, you'll at the minimum gain the terms and vocabulary to hon in on the actual question you have. Commented Sep 16, 2022 at 13:44
  • 2
    The Model us fine but you haven't shown any attempt to solve you own issue. Give it a try and we can help troubleshoot. Try the Apple SwiftUI Tutorials Commented Sep 16, 2022 at 13:45

2 Answers 2

2

try this approach to fetch your images and display them in a View:

import Foundation
import SwiftUI

struct ContentView: View {
    @StateObject var vm = ViewModel()
    
    var body: some View {
        VStack {
            Text("Fetching the data...")
            List (vm.images, id: \.self) { url in
                AsyncImage(url: URL(string: url)) { image in
                    image
                        .resizable()
                        .aspectRatio(contentMode: .fit)
                        .frame(width: 111, height: 111)
                } placeholder: {
                    ProgressView()
                }
            }
        }
        .task {
            await vm.getData()
        }
    }
}

class ViewModel: ObservableObject {
    @Published var images = [String]()
    
    func getData() async {
        guard let url = URL(string: "apiurl") else { return }
        do {
            let (data, _) = try await URLSession.shared.data(from: url)
            Task{@MainActor in
                let results = try JSONDecoder().decode(APIResponse.self, from: data)
                self.images = results.images
            }
        } catch {
            print("---> error: \(error)")
        }
    }
}

struct APIResponse: Codable {
    let images: [String]
}
Sign up to request clarification or add additional context in comments.

Comments

1
1. First you need to have a variable with data type of Data like this: var imageData: Data?

2. Then you have to fetch the image data from the link in the array like this:
func getImageData() {
        // Check image url isnt nill
        guard imageUrl(your image url) != nil else {
            return
        }
        // Download the data for the image
        let url = URL(string: imageUrl(your image url)!)
        if let url = url {
            let session = URLSession.shared
            let dataTask = session.dataTask(with: url) { data, response, error in
                if error == nil {
                    DispatchQueue.main.async {
                        self.imageData = data
                    }
                }
            }
            dataTask.resume()
        }
    }

3. Once this is done go to the view file where you want to display the image and create 

let uiImage = UIImage(data: put the var in which you stored the image data in previous step ?? Data())
 
Image(uiImage: uiImage ?? UIImage())

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.