1

login.swift主要有一个:

import SwiftUI

class GlobalEnvironment: ObservableObject {

    @Published var accountId: Int = 0
}

struct Login: View {

    @EnvironmentObject var env: GlobalEnvironment

    @State private var username: String = ""
    @State private var password: String = ""

    @State var authenticationDdidFail: Bool = false
    @State var authenticationDidSucceed: Bool = false

    var body: some View {

        if env.accountId == 0 {
            return AnyView(LoginView(username: self.$username, password: self.$password, authenticationDdidFail: self.$authenticationDdidFail, authenticationDidSucceed: self.$authenticationDidSucceed))
        } else {
            return AnyView(ContentView().environmentObject(GlobalEnvironment()))
        }


    }
}
...

该文件env.accontId在 LoginView 中设置登录后,以及成功。

然后我有一个data.swit

struct Transaction: Codable, Identifiable {
    let id = UUID()
    var purpose: String
}

class Api {

    @EnvironmentObject var env: GlobalEnvironment

    func getTransactions(completion: @escaping ([Transaction]) -> ()) {

        guard let url = URL(string: "https://url.com/api.php?get_transactions&account=\(env.accountId)") else { return }

        URLSession.shared.dataTask(with: url) { (data, _, _) in
            let transactions = try! JSONDecoder().decode([Transaction].self, from: data!)
            DispatchQueue.main.async {
                completion(transactions)
            }

        }
        .resume()

}

API 从以下位置调用Transactions.swift

import SwiftUI

struct ContentView: View {

    @EnvironmentObject var env: GlobalEnvironment

    @State var transactions: [Transaction] = []

    var body: some View {
        NavigationView {
            List(transactions) { transaction in
                Text(transaction.purpose)

                }
            .environmentObject(GlobalEnvironment())
            .onAppear {
                Api().getTransactions { (transactions) in
                    self.transactions = transactions
                }
            }
            .navigationBarTitle(Text("Transactions"))
        }
    }
}

我收到Thread 1: Fatal error: No ObservableObject of type GlobalEnvironment found. A View.environmentObject(_:) for GlobalEnvironment may be missing as an ancestor of this view.guard let url = URL(string: "https://url.com/api.php?get_transactions&account=\(env.accountId)") else { return }.

据我了解,将 GlobalEnvironment 添加到 Api 类中,它应该可以工作,但它没有。相反,我已经尝试在函数中添加它,但它也不起作用。如您所见,将 .environmentObject() 添加到列表视图本身也是如此。

4

2 回答 2

0

它一定要是:

  .environmentObject(self.env)

当然,SceneDelegate 或其他地方可能会出现更多错误。

于 2020-05-11T18:05:43.630 回答
0

您可以尝试environmentObject在通话中发送您的onAppear

.onAppear 
{
    Api().getTransactions { (transactions) in
        self.transactions = transactions
    }.environmentObject(self.env)
}
于 2020-05-11T19:15:33.003 回答