试图访问由另一个场景委托函数在场景委托内创建的环境对象

Trying to access the environment object created inside scene delegate by another scenedelegate function

我已经在我的场景代理中创建了一个环境对象,并且还想在我的场景代理中的另一个函数中使用它。代码如下所示:

SceneDelegate.swift

    class SceneDelegate: UIResponder, UIWindowSceneDelegate {
    
        var window: UIWindow?
        //@EnvironmentObject var data: DataFetcher
        var data = DataFetcher()
    
        func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
 
            if let windowScene = scene as? UIWindowScene {
                
                let window = UIWindow(windowScene: windowScene)
                let data = (UIApplication.shared.delegate as! AppDelegate).self.data
                window.rootViewController = UIHostingController(rootView: ContentView().environmentObject(data))
                self.window = window
                window.makeKeyAndVisible()
            }
        }
        
        func handleIncomingDynamicLink(_ dynamicLink: DynamicLink){
            guard let url = dynamicLink.url else {
                print("That's weird. My dynamic link object has no url")
                return
            }
            print("Your incoming link parameter is \(url.absoluteString)")
            guard let components = URLComponents(url: url, resolvingAgainstBaseURL: false),
                let queryItems = components.queryItems else {return}
            self.data.linkRecieved = true
            print(data.linkRecieved)
        }
func scene(_ scene: UIScene, continue userActivity: NSUserActivity) {
        if let incomingURL = userActivity.webpageURL {
            print("Incoming URL is \(incomingURL)")
            _ = DynamicLinks.dynamicLinks().handleUniversalLink(incomingURL) { (dynamicLink, error) in
                guard error == nil else{
                    print("Found an error! \(error!.localizedDescription)")
                    return
                }
                if let dynamicLink = dynamicLink {
                    self.handleIncomingDynamicLink(dynamicLink)
                }
            }
        }
    }
        

问题是当执行 handleIncomingDynamicLink 函数时,环境对象的 linkRecieved 变量在 contentview 中没有改变(我已经验证一旦函数 运行 变量确实改变为 true)。非常感谢解决此问题的任何见解!!!

您需要注入 var data 即 属性,因此删除以下行

let window = UIWindow(windowScene: windowScene)
//let data = (UIApplication.shared.delegate as! AppDelegate).self.data // << this one
window.rootViewController = UIHostingController(rootView: 
   ContentView().environmentObject(self.data))   // << inject own property

您已将 DataFetcher 实例分配给 data 属性,大概是为了设置其类型并消除 属性 未初始化的错误。

然后在 willConnectTo 中,您从 AppDelegate. Your dataproperty and the localdatavariable inwillConnectTo(That you subsequently add to the environment) now reference different instances ofDataFetcher` 中获取 DataFetcher 实例,但是你没有意识到。

出于这个原因,我不太喜欢将“丢弃”实例分配给属性。

更好的方法是使用隐式解包可选。这样一来,如果您不为 属性 赋值,您将崩溃并很快发现不对劲。

然后在 willConectTo 中,您可以将 AppDelegate 中的实例分配给 属性 并将其放入环境中。

class SceneDelegate: UIResponder, UIWindowSceneDelegate {
    
        var window: UIWindow?
        //@EnvironmentObject var data: DataFetcher
        var data: DataFetcher!
    
        func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
 
            if let windowScene = scene as? UIWindowScene {
                
                let window = UIWindow(windowScene: windowScene)
                self.data = (UIApplication.shared.delegate as! AppDelegate).self.data
                window.rootViewController = UIHostingController(rootView: ContentView().environmentObject(data))
                self.window = window
                window.makeKeyAndVisible()
            }
        }