Home > Mobile >  how to fetch data from nested array from API?
how to fetch data from nested array from API?

Time:09-21

this is my API

this is my Model

import Foundation

public struct Welcome: Decodable{
    public let userslist: [Userslist]

}


public struct Userslist: Decodable, Hashable{

    public let partner_media: [PartnerMedia]

    public init( partner_media: [PartnerMedia]) {
     

        self.partner_media = partner_media
    }
}

public struct PartnerMedia: Decodable , Hashable{
    public var id = UUID()
    public let url: String

    public init( url: String) {

        self.url = url
    }
}

And this is my ModelView.

class PublisherModelVM: ObservableObject {
    @Published var datas = [PartnerMedia]()
    
    let url = "https://alibrary.in/api/publisherList"
    
    init() {
        getData(url: url)
    }
    
    
    func getData(url: String) {
        guard let url = URL(string: url) else { return }
        URLSession.shared.dataTask(with: url) { (data, _, _) in
            if let data = data {
                do {
                    let results = try JSONDecoder().decode(Welcome.self, from: data)
                    DispatchQueue.main.async {

                        self.datas = results.userslist `//Cannot assign value of type '[Userslist]' to type '[PartnerMedia]' what should I write for getting proper response`
                        

                    }
                }
                catch {
                    print(error)
                }
            }
        }.resume()
    }
}

I want to fetch the url And set to the ImageView

struct PublisherListView: View{
    @StateObject var list = PublisherModelVM()
    
    var body: some View{
        ScrollView(.horizontal,showsIndicators: false){

                ForEach(list.datas, id: \.id){ item in
                    AsyncImage(url: URL(string: item.url)){image in
                        image
                            .resizable()
                            .frame(width: 235, height: 125).cornerRadius(8)
                        
                    }placeholder: {
                     
                            Image(systemName: "eye") .resizable()
                                .frame(width: 235, height: 125).cornerRadius(8)
                       
                    }
                    
                }
                
               
            }
            
            
        }
    }

this Error show in my Xcode Cannot assign value of type '[Userslist]' to type '[PartnerMedia]' Please help me. can anyone help me for recommending for API related full detailed courses and thank you in advance

CodePudding user response:

As I said before (in the questions you have deleted) pay attention to the details of your models to match the json data. Try this approach, works very well for me:

struct ContentView: View {
    var body: some View {
        PublisherListView()
    }
}

struct ServerResponse: Decodable {
    let userslist: [User]
}

struct User: Decodable, Identifiable {
    let id: Int
    let totalBooks: Int
    let totalfollowers: Int
    let fullAddress: String?
    let partnerMedia: [PartnerMedia]
    
    enum CodingKeys: String, CodingKey {
        case id, totalBooks,totalfollowers
        case partnerMedia = "partner_media"
        case fullAddress = "full_address"
    }
}

struct PartnerMedia: Decodable, Identifiable {
    let id: Int
    let url: String
}

struct PublisherListView: View{
    @StateObject var list = PublisherModelVM()
    
    var body: some View{
        ScrollView(.horizontal,showsIndicators: false){
            HStack(spacing:15) {
                ForEach(list.datas, id: \.id){ item in
                    AsyncImage(url: URL(string: item.url)){ image in
                        image
                            .resizable()
                            .frame(width: 235, height: 125).cornerRadius(8)
                        
                    } placeholder: {
                        Image(systemName: "eye") .resizable()
                            .frame(width: 235, height: 125).cornerRadius(8)
                    }
                }
            }
        }
    }
}

class PublisherModelVM: ObservableObject {
    @Published var datas = [PartnerMedia]()
    
    let url = "https://alibrary.in/api/publisherList"
    
    init() {
        getData(url: url)
    }
    
    func getData(url: String) {
        guard let url = URL(string: url) else { return }
        URLSession.shared.dataTask(with: url) { (data, _, _) in
            if let data = data {
                do {
                    let results = try JSONDecoder().decode(ServerResponse.self, from: data)
                    DispatchQueue.main.async {
                        for user in results.userslist {
                            self.datas.append(contentsOf: user.partnerMedia) 
                        }
                    }
                }
                catch {
                    print(error)
                }
            }
        }.resume()
    }
    
}
  • Related