Accessing Appstate in Appdelegate with Swiftui's New iOS 14 Life Cycle

Accessing AppState in AppDelegate with SwiftUI's new iOS 14 life cycle

Use shared instance for AppState

class AppState: ObservableObject {
static let shared = AppState() // << here !!

// Singe source of truth...
@Published var user = User()
}

so you can use it everywhere

struct MyApp: App {
@UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
@StateObject var appState = AppState.shared

// ... other code
}

and

    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
// ...and access appState here

AppState.shared.user = ...
}

How to access the Swift struct conforming to the App protocol from the AppDelegate

Inside the RelayEmulatorApp, after the socketServer has been instantiated, you can assign it to the appDelegate variable.

@main
struct RelayEmulatorApp: App {

var socketServer : SocketServer

@NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate

func someFunctionThatInstantiatesSocketServer() {
/// Instantiation for sockectServer is done at this point
appDelegate.socketServer = socketServer
}
}

Then you will have access to this instance in AppDelegate class.

class AppDelegate: NSObject, NSApplicationDelegate {

var socketServer : SocketServer

func applicationWillTerminate(_ notification: Notification) {
/// socketServer.close()
}

}

How do we register a Multiplatform App to receive notifcations in iOS 14?

Check out UIApplicationDelegateAdaptor and it’s NS* equivalent. They let you provide a class that will be used as the app delegate. Example: https://www.hackingwithswift.com/quick-start/swiftui/what-is-the-uiapplicationdelegateadaptor-property-wrapper



Related Topics



Leave a reply



Submit