简体   繁体   English

在自己的应用程序/视图中接收本地通知(或如何在 SwiftUI 中注册 UNUserNotificationCenterDelegate )

[英]receive local notifications within own app / view (or how to register a UNUserNotificationCenterDelegate in SwiftUI )

I am redeveloping an android app for iOS with SwiftUI that contains a countdown feature.我正在使用包含倒计时功能的 SwiftUI 为 iOS 重新开发 android 应用程序。 When the countdown finishes the user should be noticed about the end of the countdown.当倒计时结束时,应该通知用户倒计时结束。 The Notification should be somewhat intrusive and work in different scenarios eg when the user is not actively using the phone, when the user is using my app and when the user is using another app.通知应该有点侵入性并且在不同的情况下工作,例如当用户没有积极使用手机时,当用户正在使用我的应用程序时以及用户正在使用另一个应用程序时。 I decided to realize this using Local Notifications, which is the working approach for android.我决定使用本地通知来实现这一点,这是 android 的工作方法。 (If this approach is totally wrong, please tell me and what would be best practice) (如果这种方法完全错误,请告诉我什么是最佳做法)

However I am stuck receiving the notification when the user IS CURRENTLY using my app.但是,当用户当前使用我的应用程序时,我无法收到通知。 The Notification is only being shown in message center (where all notifications queue), but not actively popping up.通知仅显示在消息中心(所有通知排队的地方),但不会主动弹出。

Heres my code so far: The User is being asked for permission to use notifications in my CountdownOrTimerSheet struct (that is being called from a different View as actionSheet):到目前为止,这是我的代码:用户被要求允许在我的 CountdownOrTimerSheet 结构中使用通知(这是从不同的视图中调用的 actionSheet):

/**
    asks for permission to show notifications, (only once) if user denied there is no information about this , it is just not grantedand the user then has to go to settings to allow notifications 
    if permission is granted it returns true
 */
func askForNotificationPermission(userGrantedPremission: @escaping (Bool)->())
{
    UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { success, error in
        if success {
            userGrantedPremission(true)
        } else if let error = error {
            userGrantedPremission(false)
        }
    }
}

Only if the user allows permission for notification my TimerView struct is being called仅当用户允许通知我的 TimerView 结构时才被调用

                         askForNotificationPermission() { (success) -> () in
                            
                            if success
                            {
                                
                                // permission granted

                                ...
                                // passing information about the countdown duration and others..
                                ...
                                
                                userConfirmedSelection = true // indicates to calling view onDismiss that user wishes to start a countdown
                                showSheetView = false // closes this actionSheet
                            }
                            else
                            {
                                // permission denied
                                showNotificationPermissionIsNeededButton = true
                            }
                        }

from the previous View从上一个视图

                   .sheet(isPresented: $showCountDownOrTimerSheet, onDismiss: {
                        // what to do when sheet was dismissed
                        if userConfirmedChange
                        {
                            // go to timer activity and pass startTimerInformation to activity
                            programmaticNavigationDestination = .timer
                            
                        }
                    }) {
                        CountdownOrTimerSheet(startTimerInformation: Binding($startTimerInformation)!, showSheetView: $showCountDownOrTimerSheet, userConfirmedSelection: $userConfirmedChange)
                    }


                    ...


                    NavigationLink("timer", destination:
                                TimerView(...),
                               tag: .timer, selection: $programmaticNavigationDestination)
                        .frame(width: 0, height: 0)

In my TimerView's init the notification is finally registered在我的 TimerView 的初始化中,通知最终被注册

        self.endDate = Date().fromTimeMillis(timeMillis: timerServiceRelevantVars.endOfCountDownInMilliseconds_date)
        
        // set a countdown Finished notification to the end of countdown
        let calendar = Calendar.current
        let notificationComponents = calendar.dateComponents([.hour, .minute, .second], from: endDate)
        let trigger = UNCalendarNotificationTrigger(dateMatching: notificationComponents, repeats: false)
        
        
        let content = UNMutableNotificationContent()
        content.title = "Countdown Finished"
        content.subtitle = "the countdown finished"
        content.sound = UNNotificationSound.defaultCritical

        // choose a random identifier
        let request2 = UNNotificationRequest(identifier: "endCountdown", content: content, trigger: trigger)

        // add the notification request
        UNUserNotificationCenter.current().add(request2)
        {
            (error) in
            if let error = error
            {
                print("Uh oh! We had an error: \(error)")
            }
        }

As mentioned above the notification gets shown as expected when the user is everyWhere but my own app.如上所述,当用户在每个地方但我自己的应用程序时,通知会按预期显示。 TimerView however displays information about the countdown and is preferably the active view on the users device.然而,TimerView 显示有关倒计时的信息,并且最好是用户设备上的活动视图。 Therefore I need to be able to receive the notification here, but also everywhere else in my app, because the user could also navigate somewhere else within my app.因此,我需要能够在此处接收通知,但也需要在我的应用程序中的其他任何地方接收通知,因为用户还可以在我的应用程序中的其他位置导航。 How can this be accomplished?如何实现?

In this example a similar thing has been accomplished, unfortunately not written in swiftUI but in the previous common language.这个例子中已经完成了类似的事情,不幸的是不是用 swiftUI 而是用以前的通用语言编写的。 I do not understand how this was accomplished, or how to accomplish this.. I did not find anything on this on the internet.. I hope you can help me out.我不明白这是如何完成的,或者如何完成这个..我在互联网上没有找到任何东西..我希望你能帮助我。

With reference to the documentation:参考文档:

Scheduling and Handling Local Notifications 调度和处理本地通知
On the section about Handling Notifications When Your App Is in the Foreground:在关于当您的应用程序处于前台时处理通知的部分:

If a notification arrives while your app is in the foreground, you can silence that notification or tell the system to continue to display the notification interface.如果在您的应用处于前台时收到通知,您可以将该通知静音或告诉系统继续显示通知界面。 The system silences notifications for foreground apps by default, delivering the notification's data directly to your app...默认情况下,系统会静音前台应用程序的通知,将通知的数据直接传送到您的应用程序...

Acording to that, you must implement a delegate for UNUserNotificationCenter and call the completionHandler telling how you want the notification to be handled.据此,您必须为UNUserNotificationCenter实现一个委托并调用completionHandler告诉您希望如何处理通知。 I suggest you something like this, where on AppDelegate you assign the delegate for UNUserNotificationCenter since documentation says it must be done before application finishes launching (please note documentation says the delegate should be set before the app finishes launching):我建议您这样做,在AppDelegate上您为UNUserNotificationCenter分配委托,因为文档说必须在应用程序完成启动之前完成(请注意文档说应该在应用程序完成启动之前设置委托):

// AppDelegate.swift
class AppDelegate: NSObject, UIApplicationDelegate {
    func application(_ application: UIApplication, willFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
        UNUserNotificationCenter.current().delegate = self
        return true
    }
}

extension AppDelegate: UNUserNotificationCenterDelegate {
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        // Here we actually handle the notification
        print("Notification received with identifier \(notification.request.identifier)")
        // So we call the completionHandler telling that the notification should display a banner and play the notification sound - this will happen while the app is in foreground
        completionHandler([.banner, .sound])
    }
}

And you can tell SwiftUI to use this AppDelegate by using the UIApplicationDelegateAdaptor on your App scene:您可以通过在您的App场景中使用UIApplicationDelegateAdaptor来告诉 SwiftUI 使用此AppDelegate

@main
struct YourApp: App {
    @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate

    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

This approach is similar to Apple's Fruta: Building a Feature-Rich App with SwiftUI这种方法类似于 Apple 的 Fruta:Building a Feature-Rich App with SwiftUI

https://developer.apple.com/documentation/swiftui/fruta_building_a_feature-rich_app_with_swiftui https://developer.apple.com/documentation/swiftui/fruta_building_a_feature-rich_app_with_swiftui

Apple have used In-app purchases this way苹果以这种方式使用应用内购买


This class holds all your code related to Notification.这个 class 包含与通知相关的所有代码。

class LocalNotificaitonCenter: NSObject, ObservableObject {
    //  .....
}

In your @main App struct, define LocalNotificaitonCenter as a @StateObject and pass it as an environmentObject to sub-views@main App 结构中,将LocalNotificaitonCenter定义为@StateObject并将其作为environmentObject传递给子视图

@main
struct YourApp: App {
    @Environment(\.scenePhase) private var scenePhase
    
    @StateObject var localNotificaitonCenter = LocalNotificaitonCenter()
    
    var body: some Scene {
        WindowGroup {
            ContentView()
                .environmentObject(localNotificaitonCenter)
        }
    }
}

It is just that!就是这样!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 当应用未运行时,UNUserNotificationCenterDelegate didReceive未收到对本地通知的响应 - UNUserNotificationCenterDelegate didReceive response for Local Notifications not called when app is not running 如何在应用程序委托之外注册本地通知? - How to register for local notifications OUTSIDE of the app delegate? 如何在SwiftUI视图中访问自己的window? - How to access own window within SwiftUI view? 如何注册cocoa应用程序以接收远程通知以更新UI? - How can I register a cocoa app to receive remote notifications to update the UI? 注册以获取远程和本地通知 - Register for Remote AND Local Notifications 如何在AWS SNS中注册iOS设备令牌以接收推送通知? - How to register iOS device token in aws sns to receive push notifications? 删除并重新安装iphone应用程序后接收本地通知 - Receive local notifications after deleting and reinstalling an iphone app 如何在应用程序处于后台时接收Darwin通知 - How to Receive Darwin Notifications when app is in background 我的iPhone应用程序可以注册接收其他应用程序的推送通知吗? - Can my iPhone app register to receive push notifications meant for another app? 使用 SwiftUI 时在分屏视图上接收应用程序之间焦点更改的通知 - Receive notifications for focus changes between apps on Split View when using SwiftUI
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM