我已經在使用AppDelegate向 APN 注冊,但由于它不支持由SceneDelegate處理的applicationWillResignActive()和applicationWillEnterForeground()函式,如此處所述。
我希望兩個代表都可以訪問我的客戶端實體。目前,AppDelegate將客戶端實體化為其屬性,然后將其作為environmentObject傳遞給場景:
import SwiftUI
@main
struct app1App: App {
@UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
var body: some Scene {
WindowGroup {
MainView().environmentObject(appDelegate.client)
}
}
}
class AppDelegate: NSObject, UIApplicationDelegate {
let client : Client = Client()
// other Notifications related functions
}
當我在視圖中宣告我的客戶時:
@EnvironmentObject var client: Client
然后視圖可以訪問客戶端的方法,但是,當我在 SceneDelegate 中宣告它時,相同的方法不起作用:
class SceneDelegate: NSObject, UIWindowSceneDelegate {
@EnvironmentObject var client: Client
func sceneWillEnterForeground(_ scene: UIScene) {
self.client.disconnect() // This fails in runtime!!!
}
}
錯誤說它需要一個可觀察的物件,但我的物件是 environmentObject:
Thread 1: Fatal error: No ObservableObject of type Client found. A View.environmentObject(_:) for Client may be missing as an ancestor of this view.
通過 SceneDeleagte 的功能提供對客戶端的訪問的正確方法是什么?
uj5u.com熱心網友回復:
只需要幫助在兩位代表之間共享客戶端 - 有什么建議嗎?
如果要在應用程式范圍內共享,那么最簡單的方法是將其設為全域
let client : Client = Client() // << create here
class AppDelegate: NSObject, UIApplicationDelegate {
// access `client` here directly
// other Notifications related functions
}
class SceneDelegate: NSObject, UIWindowSceneDelegate {
func sceneWillEnterForeground(_ scene: UIScene) {
// access `client` here directly
client.disconnect() // This fails in runtime!!!
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/497949.html
