UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

How to fetch data (Array)from API

Forums > SwiftUI

@Anoop  

This is My JSON :--

{
"publisherPlans": [
[
"Name",
"Free",
"Prime"
],
[
"Book Sell",
9999,
9999
],
[
"Book Bulk Sell",
0,
9999
],
[
"Magazine start-up",
9999,
9999
],
[
"Demo book request count for School",
5,
9999
],
[
"Demo book request Acception",
9999,
9999
],
[
"Assign book for demo",
25,
9999
],
[
"Upload PDF",
30,
150
],
[
"Upload PDF Size",
300,
1636
],
[
"Upload PDF Pages",
2500,
5000
],
[
"Margin of profits",
70,
100
],
[
"Durability End",
90,
9999
],
[
"Create Story",
5,
10
],
[
"Read Story",
50,
9999
],
[
"Create Stack",
5,
20
],
[
"Read Credit Addition",
9999,
9999
],
[
"Read Credit Withdraw",
0,
9999
]
]
}

This is My Model:--

import Foundation

public struct SchoolPlanModel:Decodable {

    public let schoolPlans: SchoolPlans

}

public struct SchoolPlans:Decodable {
    public let thead: [[[String]]]
    public let tbody: [[[Tbody]]]

}

public enum Tbody: Decodable {
    case integer(Int)
    case string(String)
}

//This Is View Here I want to show my All Data of API.

struct SchoolPlanView: View{
    @StateObject var list = ReadData()

    var body: some View{
//        ForEach(0..<list.datas.indices){ item in
        Text("\(list.datas[0])")

//        }

    }
}

//This is View Model 
class ReadData: ObservableObject {
    @Published var datas = [String]()

    func getData() async {
        guard let url = URL(string: "https://www.alibrary.in/api/alib-plans") else { return }
        do {
            let (data, _) = try await URLSession.shared.data(from: url)
            Task{@MainActor in
                let results = try JSONDecoder().decode(SchoolPlanModel.self, from: data).schoolPlans

            }
        } catch {
            print("---> error: \(error)")
        }
    }
}

And I don't know how can I fetch detail and set to the View?

1      

@Anoop  


struct PlanModel: Decodable {
var publisherPlans: [[PublisherPlan]]
var schoolPlans: [[PublisherPlan]]

}

enum PublisherPlan: Decodable, Hashable {
case integer(Int)
case string(String)

// -- here
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
if let x = try? container.decode(Int.self) {
self = .integer(x)
return
}
if let x = try? container.decode(String.self) {
self = .string(x)
return
}
throw DecodingError.typeMismatch(PublisherPlan.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Wrong type for Plan"))
}
}

class ReadData: ObservableObject {
@Published var datas: [[PublisherPlan]] = []  // <-- here

func getData() async {
guard let url = URL(string: "**************urlapi") else { return }
do {
let (data, _) = try await URLSession.shared.data(from: url)
Task{@MainActor in
let results = try JSONDecoder().decode(PlanModel.self, from: data)
self.datas = results.publisherPlans // <-- here
}
} catch {
print("---> error: \(error)")
}
}
}

struct SchoolsPlansView_Previews: PreviewProvider {
static var previews: some View {

SchoolsPlansView()

}
}

struct SchoolsPlansView: View{
@StateObject var list = SchoolPlanViewModel()

var body: some View {
ZStack {
Image("u").resizable().ignoresSafeArea()
VStack{
Spacer()
VStack {
Spacer(minLength: 80)
ScrollView(showsIndicators: false){
VStack{

HStack(alignment: .center, spacing: nil) {

ForEach(list.schoolPlanHeading, id: \.self){ heading in
Text("**\(heading)**").font(.system(size: 22))

}.frame(maxWidth: UIScreen.main.bounds.width/3.1, alignment: .center)
//                                .border(.gray, width: 2)

}
.padding()

ForEach(list.schoolPlanData, id: \.self) { array in
HStack(alignment: .center, spacing: nil) {

ForEach(array, id: \.self){ item in
switch item {
case .integer(let int):
if int == 9999 {
Image(systemName: "checkmark.circle.fill").foregroundColor(.green.opacity(0.8)).font(.system(size: 28))

}
else if int == 0{
Image(systemName: "multiply.circle.fill").foregroundColor(.red.opacity(0.8)).font(.system(size: 28))
}

else{
Text("\(int)").font(.system(size: 24))
}
//
case .string(let str): Text(str).font(.system(size: 18))
}

}.frame(maxWidth: UIScreen.main.bounds.width/3.1, alignment: .center)
//                                .border(.gray, width: 2)

}
.padding()
}

}
.frame(width: UIScreen.main.bounds.width*0.9).background(Color.white).border(.gray, width: 0.2).cornerRadius(12)
Text("**Read credit upgrade**\nReading Prime Books or Prime Magazines will cost 1 Read Credit(RC) by dafault. In case of full consumption of Read Credits(RC) during Prome Membership, Readers are requested to top up by purchasing Read Credits(RC) as per their reading habit.")
}
.padding(1)
}

Text("**Purchase Now**").font(.system(size: 26)).foregroundColor(.white).frame(width: UIScreen.main.bounds.width*0.8, height: 65).background(Color.green).cornerRadius(28)
.padding()
Spacer(minLength: 80)
}
}.task {
await list.getData()
}

}
}

class SchoolPlanViewModel: ObservableObject {

@Published var schoolPlanData: [[PublisherPlan]] = []
//    @Published var headings: [String] = []  // <-- here
@Published var schoolPlanHeading: [String] = []

func getData() async {
guard let url = URL(string: "**************urlapi") else { return }
do {
let (data, _) = try await URLSession.shared.data(from: url)
//       print("\n \(String(data: data, encoding: .utf8) as AnyObject) \n")
Task{@MainActor in
let results = try JSONDecoder().decode(PlanModel.self, from: data)
// the data minus the first array of headings
schoolPlanData = Array(results.schoolPlans.dropFirst()) // <-- here

// get the headings

if let headers = results.schoolPlans.first { // <-- here

for h in headers {
switch h {
case .integer(_): break
case .string(let str):
if self.schoolPlanHeading.count < 3{
self.schoolPlanHeading.append(str)
}

}
}
}

}
} catch {
print("---> error: \(error)")
}
}
}

1      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.