简体   繁体   English

将数据从委托 Swift Class 传递到 SwiftUI 结构中的 EnvironmentObject

[英]Passing Data from Delegate Swift Class to EnvironmentObject in SwiftUI Struct

How do I pass incoming data from a method triggered by a delegate in a Swift class to an EnvironmentObject?如何将来自 Swift class 中的委托触发的方法的传入数据传递给 EnvironmentObject?

I am aware that for this to work my Swift class needs to be called/initialized from the SwiftUI struct (be a child of the parent SwiftUI struct). I am aware that for this to work my Swift class needs to be called/initialized from the SwiftUI struct (be a child of the parent SwiftUI struct). However, I initialise my Swift class in the ExtensionDelegate of the Apple Watch app.但是,我在 Apple Watch 应用程序的 ExtensionDelegate 中初始化了我的 Swift class。 I would like to see the UI Text element change when the name is updated.我希望在名称更新时看到 UI 文本元素发生变化。

The following code runs on the Apple Watch:以下代码在 Apple Watch 上运行:

class User: ObservableObject {
    
    @Published var id: UUID?
    @Published var name: String?
}
//SwiftUI struct
struct UI: View {

@EnvironmentObject var userEnv: User

var body: some View {
   Text(userEnv.name)
 }
}
// Swift class
class WatchConnectivityProvider: NSObject, WCSessionDelegate {

 static let shared = WatchConnectivityProvider()
 private let session: WCSession
    
    init(session: WCSession = .default) {
        self.session = session
        super.init()
    }
    
    func activateSession() {
        if WCSession.isSupported() {
            session.delegate = self
            session.activate()
        }
    }

    //This func gets triggered when data is sent from the iPhone
    func session(_ session: WCSession, didReceiveMessage message: [String : Any], replyHandler: @escaping ([String : Any]) -> Void) {
        
        let list = message["list"]
        
        let jsonDecoder = JSONDecoder()
        if let data = try? jsonDecoder.decode(User.self, from: list as! Data) {
            
        // !!! This is where I would like to update the EnvironmentObject userEnv !!!   
        // What is the best way to do this? Remember, this class has already been initialised within the ExtensionDelegate.
        }
    }
}
//ExtensionDelegate of Apple Watch app, initialising the WatchConnectivityProvider
class ExtensionDelegate: NSObject, WKExtensionDelegate {

    func applicationDidFinishLaunching() {
        // Perform any final initialization of your application.
        WatchConnectivityProvider.shared.activateSession()
    }
}

Dependency Injection依赖注入

One of the solutions could be to store the reference to your @EnvironmentObject globally, eg.一种解决方案可能是全局存储对@EnvironmentObject的引用,例如。 in some dependency container.在一些依赖容器中。

enum Dependencies {
    struct Name: Equatable {
        let rawValue: String
        static let `default` = Name(rawValue: "__default__")
        static func == (lhs: Name, rhs: Name) -> Bool { lhs.rawValue == rhs.rawValue }
    }

    final class Container {
        private var dependencies: [(key: Dependencies.Name, value: Any)] = []

        static let `default` = Container()

        func register(_ dependency: Any, for key: Dependencies.Name = .default) {
            dependencies.append((key: key, value: dependency))
        }

        func resolve<T>(_ key: Dependencies.Name = .default) -> T {
            return (dependencies
                .filter { (dependencyTuple) -> Bool in
                    return dependencyTuple.key == key
                        && dependencyTuple.value is T
                }
                .first)?.value as! T
        }
    }
}

Then you create your object like this:然后你像这样创建你的 object:

Dependencies.Container.default.register(User())

And you can access it from anywhere in your code:您可以从代码中的任何位置访问它:

let user: User = Dependencies.Container.default.resolve()
user.modify()

A more detailed explanation of Dependency Injection for Swift can be found here . Swift 的Dependency Injection的更详细解释可以在这里找到。

Singleton Singleton

Alternatively you can use standard Singleton pattern to make your User data available globally.或者,您可以使用标准Singleton模式使您的用户数据在全球范围内可用。 A more detailed explanation can be found here .更详细的解释可以在这里找到。

Final thoughts最后的想法

Clean Architecture for SwiftUI is a good example (in my opinion at least) of how to write an iOS app in the clean way. SwiftUI 的干净架构是一个很好的例子(至少在我看来)如何以干净的方式编写 iOS 应用程序。 It's a little bit complicated, but you can pick up some parts.这有点复杂,但你可以拿起一些部分。

Here bad Jumbo code:这里糟糕的巨型代码:

class ExtensionDelegate: ObservableObject, NSObject, WCSessionDelegate, WKExtensionDelegate {
var session: WCSession?
@Published var vm = ViewModel

func session(_ session: WCSession, didReceiveMessage message: [String : Any], replyHandler: @escaping ([String : Any]) -> Void) {
    print(#function)
    var replyValues = Dictionary<String, Any>()
    replyValues["status"] = "failed"
    
    // 2442 Bytes
    if let data = message["data"] as? Data {
        // push that work back to the main thread
        DispatchQueue.main.async {
            self.vm = try? JSONDecoder().decode(ViewModel.self, from: data)
        }
        if let vm = vm {
            replyValues["status"] = "ok"
            replyValues["id"] = vm.id.uuidString
        }
    }
    replyHandler(replyValues)
}
...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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