ios - SwiftUI 2 访问 AppDelegate
问题描述
我做了一个小原型,它使用 Firebase 云消息传递和新的 SwiftUI 2 应用程序生命周期。我添加了一个自定义 AppDelegate
@UIApplicationDelegateAdaptor(AppDelegate.self) var delegate
并禁用了方法 swizzeling 以使 FCM 工作。一切都按预期工作。
今天一位同事问我,是否可以通过UIApplication.shared.delegate
. 所以我试了一下,发现似乎有两个不同的 AppDelegate 对象:
po delegate
印刷:
<MyProject.AppDelegate: 0x6000009183c0>
在哪里po UIApplication.shared.delegate
打印:
▿ Optional<UIApplicationDelegate>
▿ some : <SwiftUI.AppDelegate: 0x600000b58ca0>
现在我想知道访问 AppDelegate 的正确方法是什么?是否应该通过 an 获取它@EnvironmentalObject
并将其传递给所有视图?还是使用老式的方式 via UIApplication
?此外,我想了解为什么我最终会得到两个 AppDelegate。
提前致谢
解决方案
您MyProject.AppDelegate
的不是直接UIApplicationDelegate
的,它通过适配器传输到内部私有SwiftUI.AppDelegate
,这是真实的UIApplicationDelegate
,它将一些委托回调传播到您的实例。
所以解决方案可能是:
如果
@EnvironmentalObject
您需要访问您MyProject.AppDelegate
唯一的 SwiftUI 视图层次结构,请使用添加和使用
MyProject.AppDelegate
通过适配器创建的对象初始化的静态属性,例如
class AppDelegate: NSObject, UIApplicationDelegate {
static private(set) var instance: AppDelegate! = nil
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
AppDelegate.instance = self // << here !!
return true
}
}
现在在您的代码中的任何地方,您都可以通过AppDelegate.instance
.
推荐阅读
- javascript - React Native 将生成的 javascript 包存储在哪里?
- excel - MS Word 表 - 请求的集合成员不存在
- python-3.x - 使用安全 SSL 套接字进行多处理
- odata - 如何在 UI5 应用程序中使用 oModel.read 查看单个条目
- java - 是否可以在没有用户操作的情况下上传文件,或者只是 html 中的对话框,角度?
- android - 为什么包含 firebase 引用时,android 应用程序在启动后立即崩溃?
- r - 计算向量中的最小值,其中最小值按连续顺序排列
- javascript - 单击按钮时我无法增加变量的值
- wix - 如果没有管理员权限,从我的 .MSI 安装的程序将无法启动
- python - SQLite 无法读取使用 Python 创建的表