在SwiftUI 5.1中,我想使用AppDelegate创建一个userData对象。 userData还将包含BLE广告数据,这些数据也将从AppDelegate中更新。这些数据应该对UI可用,以便显示这些值。
在AppDelegate中,我使用:
在SceneDelegate中,我希望使用以下方法将传递到视图中:
在AppDelegate中,我使用:
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
private var centralManager : CBCentralManager!
var userData: UserData!
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
userData = UserData()
return true
}
在SceneDelegate中,我希望使用以下方法将传递到视图中:
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
@EnvironmentObject var userData: UserData
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
// Use a UIHostingController as window root view controller
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
window.rootViewController = UIHostingController(rootView:
BeaconList().environmentObject(userData)
)
self.window = window
window.makeKeyAndVisible()
}
}
编译没有问题,但在运行代码时出现以下错误:
Thread 1: 致命错误: 在View.body之外读取EnvironmentObject
如果我删除
.environmentObject(userData)
我会得到
Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)
实际上,我试图从AppDelegate创建和更新userData对象,并从SceneDelegate和下面的视图中显示。
我应该如何实现这个?
SceneDelegate
呢?这是苹果要求处理此类问题的方式。(也许你发现了一种没有覆盖到的情况,但我怀疑这种情况存在。) - user7014451userData
实例? - Peter Schorn