5

在搜索了 Apple 的 SwiftUI 文档、web 和 stackoverflow 之后,我似乎无法弄清楚如何使用多个类并在它们之间传递 EnviromentObject 数据。所有关于 SwiftUI 的 EnvironmentObject、ObservableObjects、Bindings 的文章都展示了如何将数据从模型传递到视图,但是从一个模型传递到另一个模型呢?或者我是否完全以错误的方式思考这个问题。

如何将 @Published 变量从 A 类传递到 B 类?

在这个简单的 SwiftUI 示例应用程序中,我尝试将 @Published 数据从 Settings 类传递到 NetworkManager 类。此应用程序有一个 ContentView,其中包含用户名和密码的两个表单字段,以及一个按钮,按下该按钮将联系 API 并显示结果。

下面的代码会崩溃,因为 NetworkManager mockService 函数不知道“设置”是什么。我可以在视图中读取“设置”观察到的 EnvironmentObject,但是如何在另一个类中获取该数据?我猜这里与绑定有关,但不确定该怎么做。

场景委托:

...
var settings = Settings()
var networkManager = NetworkManager()

...
let contentView = ContentView()
    .environmentObject(settings)
    .environmentObject(networkManager)
...

内容视图.swift

class Settings: ObservableObject {
    @Published var username: String = ""
    @Published var password: String = ""    
}

// This function in reality will be rewritten and expanded with multiple networking calls
class NetworkManager: ObservableObject {
    @Published var token: String = ""

    func mockService() {
        token = settings.username + settings.password
    }
}

struct ContentView: View {
    @EnvironmentObject var settings: Settings
    @EnvironmentObject var networkManager: NetworkManager
    var body: some View {
        VStack {
            TextField("Username", text: $settings.username)
            TextField("Password", text: $settings.password)
            Button("Update"){
                self.networkManager.mockService()
            }
            Divider()
            Text("\(networkManager.token)")

        }
    }
}
4

1 回答 1

0

这是使网络对象了解设置对象的一种方法,但我认为这不是最好的方法,您可以尝试一下:

class Settings: ObservableObject {
    @Published var username: String = ""
    @Published var password: String = ""
    var currentSettingsPublisher: PassthroughSubject<Settings,Never> = .init()

    var cancellablesBag: Set<AnyCancellable> = []


    init() {
        observeChanges()
    }

    // Object will change is called to notify subscribers about changes( That's how swiftUI react to changes)
    private func observeChanges() {

        self.objectWillChange.sink { [weak self] (_) in
            guard let self = self else { return }
            self.currentSettingsPublisher.send(self)
        }.store(in: &cancellablesBag)
    }
}

// This function in reality will be rewritten and expanded with multiple networking calls
class NetworkManager: ObservableObject {
    
    @Published var token: String = ""
    var cancellablesBag: Set<AnyCancellable> = []
    var currentSettingsPublisher: AnyPublisher<Settings,Never>
    private var settings: Settings?

    init(_ settings: AnyPublisher<Settings,Never>) {
        self.currentSettingsPublisher = settings
        observeSettings()
    }

    func observeSettings() {
        currentSettingsPublisher
            // .debounce(for: .seconds(0.5), scheduler: RunLoop.main) maybe you can use debounce to debounce updating of your settings object
            .sink { [weak self] (newSettings) in
            guard let self = self else { return }
                print("i have the new settings")
            self.settings = newSettings
        }.store(in: &cancellablesBag)
    }
    

    
    func mockService() {
        guard let settings = settings else {
            return assertionFailure("Settings is nil, what to do ?")
        }

        token = settings.username + settings.password
        print("new token: \(token)")
    }
}

struct ContentView: View {
    @EnvironmentObject var settings: Settings
    @EnvironmentObject var networkManager: NetworkManager
    var body: some View {
        VStack {
            TextField("Username", text: $settings.username)
            TextField("Password", text: $settings.password)
            Button("Update"){
                self.networkManager.mockService()
            }
            Divider()
            Text("\(networkManager.token)")

        }
    }
}

对于 SceneDelegate

var settings = Settings()
var networkManager: NetworkManager!

        func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {

networkManager = 
    NetworkManager(settings.currentSettingsPublisher.eraseToAnyPublisher())
            
    
            let contentView = ContentView()
                .environmentObject(settings)
                .environmentObject(networkManager)

}
于 2021-05-24T01:37:14.627 回答