Anup Kumar Mishra
Anup Kumar Mishra

Reputation: 206

how to fetch data from array by indexing in SwiftUI?

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
    }
}

Upvotes: -1

Views: 432

Answers (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]
}

Upvotes: 2

Amish
Amish

Reputation: 141

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())

Upvotes: 1

Related Questions