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
Module Compiled With Swift 3.0 Cannot Be Imported in Swift 3.0.1
How to Convert Hex Number to Bin in Swift
How to Use Contains Within a Swift Array Extension
How to Perform an Action Only After Data Are Downloaded from Firebase
How to Determine the Type of a Variable in Swift
Draw on a PDF Using Swift on MACos
Swift - Could Not Cast Value of Type '_Nscfstring' to 'Nsdictionary'
Swift Custom Context Menu Previewprovider Can Not Click Any View Inside(Using Tapgesture)
Use Resources in Unit Tests with Swift Package Manager
How to Document the Parameters of a Function'S Closure Parameter in Swift 3
Accessing Appstate in Appdelegate with Swiftui's New iOS 14 Life Cycle
How to Make the Scroll of a Tableview Inside Scrollview Behave Naturally
Delete Data from Coredata Swift