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

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

我正在使用包含倒计时功能的 SwiftUI 重新开发适用于 iOS 的 Android 应用程序。当倒计时结束时,应该通知用户倒计时结束。通知应该有点侵入性并且在不同的场景中工作,例如当用户没有主动使用手机时,当用户正在使用我的应用程序以及用户正在使用另一个应用程序时。我决定使用本地通知来实现这一点,这是 android 的工作方法。 (如果这种方法完全错误,请告诉我以及最佳做法是什么)

但是,当用户当前使用我的应用程序时,我无法接收通知。通知仅显示在消息中心(所有通知队列中),但不会主动弹出。

这是我目前的代码: 用户被要求允许在我的 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)
        }
    }
}

仅当用户允许通知权限时,我的 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
                            }
                        }

来自上一个视图

                   .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)

在我的 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)")
            }
        }

如上所述,当用户无处不在但我自己的应用程序时,通知会按预期显示。但是 TimerView 显示有关倒计时的信息,并且最好是用户设备上的活动视图。因此,我需要能够在此处接收通知,而且还需要在我的应用程序中的其他任何地方接收通知,因为用户还可以在我的应用程序中的其他地方导航。如何实现?

this example 中已经完成了类似的事情,不幸的是不是用 swiftUI 编写的,而是用以前的通用语言编写的。我不明白这是如何完成的,或者如何完成这个.. 我在互联网上没有找到任何关于这个的东西.. 希望你能帮助我。

解决方法

参考文档:

Scheduling and Handling Local Notifications
关于当您的应用处于前台时处理通知部分:

如果您的应用在前台时收到通知,您可以 使该通知静音或告诉系统继续显示 通知界面。系统将通知静音 默认情况下前台应用程序,传递通知的数据 直接到您的应用...

据此,您必须为 UNUserNotificationCenter 实现一个委托,并调用 completionHandler 告诉您希望如何处理通知。 我建议你这样做,在 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])
    }
}

并且您可以通过在 AppDelegate 场景中使用 UIApplicationDelegateAdaptor 来告诉 SwiftUI 使用此 App

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

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

这种方法类似于 Apple 的 Fruta:使用 SwiftUI 构建功能丰富的应用

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

Apple 已经通过这种方式使用应用内购买


这个类包含所有与通知相关的代码。

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

在您的 @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)
        }
    }
}

就是这样!

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 <select id="xxx"> SELECT di.id, di.name, di.work_type, di.updated... <where> <if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 <property name="dynamic.classpath" value="tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams['font.sans-serif'] = ['SimHei'] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -> systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping("/hires") public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate<String
使用vite构建项目报错 C:\Users\ychen\work>npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-