read
This template is for multiplatform app supporting both iOS and macOS in the same target.
Even though we now have SwiftUI App
struct, app delegates are still often needed eg. launch sequence, more lifecycle events, handle push notifications
However, iOS UIApplicationDelegate and macOS NSApplicationDelegate are different objects, and I often have this boilerplate code.
#if canImport(UIKit)
import UIKit
final class AppDelegate: NSObject, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
return true
}
/// Received APNS token
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let token = deviceToken.map { String(format: "%.2x", $0) }.joined()
}
/// Received push notification
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
completionHandler(.newData)
}
}
#elseif canImport(AppKit)
import AppKit
final class AppDelegate: NSObject, NSApplicationDelegate {
func applicationDidFinishLaunching(_ notification: Notification) {
}
/// Received APNS token
func application(_ application: NSApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let token = deviceToken.map { String(format: "%.2x", $0) }.joined()
}
/// Received push notification
func application(_ application: NSApplication, didReceiveRemoteNotification userInfo: [String : Any]) {
}
}
#endif
In SwiftUI App
Similarly, using platform conditional code, add the app delegate adaptor.
@main
struct MyApp: App {
#if canImport(UIKit)
@UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
#elseif canImport(AppKit)
@NSApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
#endif
}