简体   繁体   中英

Store the number of incoming data in API

in SwiftUI

I'm trying to count the number of data in API To display on the View

When I print a variable @Published var counts = 0 in the same class, I see that the value coming from API has been saved

But when it is displayed on the View comes the default value

Do I have an error in the method of transferring data or is there something else?

class Api : ObservableObject{

@Published var counts = 0

func getData(complation: @escaping ([model]) -> ()) {
    
    guard let url = URL(string: "https://XXXXXX") else { return }
    let token = "28|cSXXXXXX"
    var request = URLRequest(url: url)
    
    request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
    
    URLSession.shared.dataTask(with: request) { data, responce, err in
        
        guard let data = data else { return }

        do {
            let dataModel = try JSONDecoder().decode([model].self, from: data)

            self.counts = dataModel.count
            
            DispatchQueue.main.async {
                complation(dataModel)
                
            }
        } catch {
            print("error: ", error)
        }
    }
    .resume()
}
}

here view

import SwiftUI

struct Tap1Section1: View {


@ObservedObject var countid = Api()
@State var modelname : [model] = [model(title: "")]

var body: some View {
    
    VStack {

        ForEach(modelname) { item in
           
            Text("\(countid.counts)")
        }
    }
    .onAppear {
        Api().getData { item in
            self.modelname = item
        }
    }
}
}

you could try the following alternative approach to get the count of your models:

struct Tap1Section1: View {
    
    @StateObject var viewModel = Api() // <-- here
    
    var body: some View {
        VStack {
            Text("\(viewModel.models.count)")  // <-- here
            ForEach(viewModel.models) { item in  // <-- here
                Text(item.title)  // <-- here
            }
        }
        .onAppear {
            viewModel.getData()
        }
    }
}

//  -- here
struct Model: Identifiable, Decodable {
    let id = UUID()
    var title: String
}

class Api: ObservableObject {
    
    @Published var models: [Model] = []  // <-- here
    
    func getData() {
        guard let url = URL(string: "https://XXXXXX") else { return }
        let token = "28|cSXXXXXX"
        var request = URLRequest(url: url)
        request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization")
        URLSession.shared.dataTask(with: request) { data, responce, err in
            guard let data = data else { return }
            do {
                let dataModel = try JSONDecoder().decode([Model].self, from: data)
                DispatchQueue.main.async {
                    self.models = dataModel  // <-- here
                }
            } catch {
                print("error: ", error)
            }
        }
        .resume()
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM