我已经在我的场景代理中创建了一个环境对象,并且还想在驻留在场景代理中的另一个函数中使用它。代码如下:
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函数时,环境对象的linkRecived变量在contentview中没有更改(我已经验证了该函数运行后该变量确实更改为true(。非常感谢您对解决此问题的任何见解!!!
您已经为data
属性分配了一个DataFetcher
实例,大概是为了设置其类型并消除属性未初始化的错误。
然后在willConnectTo
中,您从您的AppDelegate. Your
数据property and the local
数据variable in
将连接到(That you subsequently add to the environment) now reference different instances of
DataFetcher`中获得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()
}
}
您需要注入属性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