我想在 SwiftUI 的屏幕上显示本地通知时捕获一个事件

问题描述 投票:0回答:0

我是从Android开发来到SwiftUI的。在工作中,我们决定尝试使用 KMM,如果不是我,谁会在没有任何学科知识的情况下回应处理 IOS 部分。

问题是我无法理解哪里有事件或某种回调来捕捉屏幕上显示通知的时刻。

我提前道歉,也许这个问题对 iOS 开发人员来说似乎很不愉快。欢迎任何关于最佳实践的批评和建议。

据我所知,这是通知本身的实现和委托的实现,其中有通过在后台和前台单击通知调用的方法。但这并不是我所需要的,我需要准确地修复通知在屏幕上显示的时刻。

private func scheduleNotification(delayTime: Double) {
        let center = UNUserNotificationCenter.current()
        center.requestAuthorization(options: [.alert, .sound, .badge]) { result, error in
            if let error = error {
                print(error)
            }
            let content = UNMutableNotificationContent()
            content.title = "title"
            content.body = "body"
            let triger = UNTimeIntervalNotificationTrigger(timeInterval: delayTime, repeats: false)
            let request = UNNotificationRequest(identifier: "my_id", content: content, trigger: triger)
            center.add(request) { error in
                if let error = error {
                    print(error)
                }
            }
        }
    }
class AppDelegate: NSObject, UIApplicationDelegate {
    
    func application(_ application: UIApplication, willFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
        UNUserNotificationCenter.current().delegate = self
        return true
    }
}

extension AppDelegate: UNUserNotificationCenterDelegate {
    /** Handle notification when app is in background */
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response:
                                UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        let notiName = Notification.Name(response.notification.request.identifier)
        NotificationCenter.default.post(name:notiName , object: response.notification.request.content)
        completionHandler()
    }
    
    /** Handle notification when the app is in foreground */
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification,
                                withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        let notiName = Notification.Name( notification.request.identifier )
        NotificationCenter.default.post(name:notiName , object: notification.request.content)
        completionHandler([.banner, .sound, .badge])
    }
}
@main
struct iOSApp: App {
    
    @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
    
    var body: some Scene {
        ...
    }
}
ios swift swiftui apple-push-notifications
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.