每日本地通知不起作用

2023-12-03

我的问题是我正在尝试安排每天在特定时间发出的通知,这是我的代码

import SwiftUI

struct notifView: View {
    var body: some View {
        VStack {
            VStack {
                Button("Request Permission") {
                    let center = UNUserNotificationCenter.current()

                    center.requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in
                        if granted {
                            print("Access Granted!")
                        } else {
                            print("Access Not Granted")
                        }
                    }
                }
                .frame(width: 200, height: 60, alignment: .center)
                .foregroundColor(.black)
                .background(Color.blue)
                .cornerRadius(10.0)
                .padding()
                Button("Add Notifications For Morning") {
                    func scheduleNotification() {
                        let center = UNUserNotificationCenter.current()

                        let content = UNMutableNotificationContent()
                        content.title = "Morning Time"
                        content.body = "Wake Up And Be Productive!"
                        content.categoryIdentifier = "reminder"
                        content.sound = UNNotificationSound.default

                        var dateComponents = DateComponents()
                        dateComponents.hour = 6
                        dateComponents.minute = 30
                        let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)

                        let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
                        center.add(request)
                    }
                }
                .padding()
                Button("Add Notifications For Middle Of The Day") {
                    func scheduleNotification() {
                        let center = UNUserNotificationCenter.current()

                        let content = UNMutableNotificationContent()
                        content.title = "Middle Of The Day"
                        content.body = "Did you have your daily run?"
                        content.categoryIdentifier = "reminder"
                        content.sound = UNNotificationSound.default

                        var dateComponents = DateComponents()
                        dateComponents.hour = 12
                        dateComponents.minute = 30
                        let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)

                        let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
                        center.add(request)
                    }
                }
                .padding()
                Button("Add Notifications For Night") {
                    func scheduleNotification() {
                        let center = UNUserNotificationCenter.current()

                        let content = UNMutableNotificationContent()
                        content.title = "Night Time"
                        content.body = "Time to sleep"
                        content.categoryIdentifier = "reminder"
                        content.sound = UNNotificationSound.default

                        var dateComponents = DateComponents()
                        dateComponents.hour = 20
                        dateComponents.minute = 51
                        let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)

                        let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
                        center.add(request)
                    }
                }
                .foregroundColor(.blue)
                .padding()
            }
        }
    }
}

struct notifView_Previews: PreviewProvider {
    static var previews: some View {
        notifView()
    }
}

看一下代码中的注释

import SwiftUI
//struct and class should start with an uppercase
struct NotificationView: View {
    //Central location for Notification code including the delegate
    // A call to the notificationManager just like the line of code below has to be included in
    // application(_:willFinishLaunchingWithOptions:) or
    // application(_:didFinishLaunchingWithOptions:)
    //https://developer.apple.com/documentation/usernotifications/unusernotificationcenterdelegate
    //https://www.hackingwithswift.com/quick-start/swiftui/how-to-add-an-appdelegate-to-a-swiftui-app
    let notificationManager: NotificationManager = NotificationManager.shared
    var body: some View {
        VStack {
            VStack {
                Button("Request Permission") {
                    //Call a func here don't define it
                    notificationManager.requestAuthorization()
                }
                .frame(width: 200, height: 60, alignment: .center)
                .foregroundColor(.black)
                .background(Color.blue)
                .cornerRadius(10.0)
                .padding()
                Button("Add Notifications For Morning") {
                    //Unique date components
                    var dateComponents = DateComponents()
                    dateComponents.hour = 6
                    dateComponents.minute = 30
                    //Reusable method
                    self.notificationManager.scheduleTriggerNotification(title: "Morning Time", body: "Wake Up And Be Productive!", categoryIdentifier: "reminder", dateComponents: dateComponents, repeats: true)
                }
                .padding()
                Button("Add Notifications For Middle Of The Day") {
                    var dateComponents = DateComponents()
                    dateComponents.hour = 12
                    dateComponents.minute = 30
                    //Reusable method
                    self.notificationManager.scheduleTriggerNotification(title: "Middle Of The Day", body: "Did you have your daily run?", categoryIdentifier: "reminder", dateComponents: dateComponents, repeats: true)
                    
                }
                .padding()
                Button("Add Notifications For Night") {
                    var dateComponents = DateComponents()
                    dateComponents.hour = 20
                    dateComponents.minute = 51
                    //Reusable method
                    self.notificationManager.scheduleTriggerNotification(title: "Night Time", body: "Time to sleep", categoryIdentifier: "reminder", dateComponents: dateComponents, repeats: true)
                    
                }
                .foregroundColor(.blue)
                .padding()
                
                Button("Print Notifications") {
                    //Reusable method
                    self.notificationManager.printNotifications()
                }
                .foregroundColor(.blue)
                .padding()
                Button("Delete Notifications") {
                    //Reusable method
                    self.notificationManager.deleteNotifications()
                }
                .foregroundColor(.blue)
                .padding()
            }
        }
    }
}
//You need a central location for the notification code because
// it is needed in more than 1 spot. At launch in the AppDelegate
// and wherever you schedule your notifications
class NotificationManager: NSObject, UNUserNotificationCenterDelegate{
    //Singleton is requierd because of delegate
    static let shared: NotificationManager = NotificationManager()
    let notificationCenter = UNUserNotificationCenter.current()
    
    private override init(){
        super.init()
        //This assigns the delegate
        notificationCenter.delegate = self
    }
    
    func requestAuthorization() {
        print(#function)
        notificationCenter.requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in
            if granted {
                print("Access Granted!")
            } else {
                print("Access Not Granted")
            }
        }
    }
    
    func deleteNotifications(){
        print(#function)
        notificationCenter.removeAllPendingNotificationRequests()
    }
    ///This is just a reusable form of all the copy and paste you did in your buttons. If you have to copy and paste make it reusable.
    func scheduleTriggerNotification(title: String, body: String, categoryIdentifier: String, dateComponents : DateComponents, repeats: Bool) {
        print(#function)
        let content = UNMutableNotificationContent()
        content.title = title
        content.body = body
        content.categoryIdentifier = categoryIdentifier
        content.sound = UNNotificationSound.default
        
        let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: repeats)
        
        let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
        notificationCenter.add(request)
    }
    ///Prints to console schduled notifications
    func printNotifications(){
        print(#function)
        notificationCenter.getPendingNotificationRequests { request in
            for req in request{
                if req.trigger is UNCalendarNotificationTrigger{
                    print((req.trigger as! UNCalendarNotificationTrigger).nextTriggerDate()?.description ?? "invalid next trigger date")
                }
            }
        }
    }
    //MARK: UNUserNotificationCenterDelegate
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        
        completionHandler(.banner)
    }
}
struct NotificationView_Previews: PreviewProvider {
    static var previews: some View {
        NotificationView()
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

每日本地通知不起作用 的相关文章

随机推荐

  • 展开转场不触发

    我学习得很快 并为我的大部分应用程序奠定了基础 我有以下故事板 应用故事板 一切正常 例如 我在添加课程视图控制器上有一个展开转场 当您按下 保存 并且您返回到 您的课程 视图控制器时 该控制器会触发 当您在我的课程视图控制器上时 您可以选
  • Checkedtextview 滚动Listview后选中/取消选中

    我正在使用 viewHolder 和 getview 在 listvew 中开发 checktextview 填充检查 取消检查状态绑定从数据库运行良好 但是 如果我选中项目然后滚动列表视图 它将返回取消选中 这是我的自定义适配器代码 pu
  • SQLite 存储、检索和比较 DATETIME 字段

    我真的很难在 Objective C 中比较 SQLite 查询中的日期 这就是我正在做的事情 存储日期 这个文件告诉我使用下面指定的日期格式 但它似乎不正确 我尝试使用yyyy MM dd hh mm ss但也没有成功 NSDate to
  • 堆栈中的 Activity 过多会使应用程序变得非常慢

    最近我创建了一个社交应用程序 我没有使用fragment 项目快完成了 我有几个活动 例如用户配置文件 关注者 关注者活动 通常情况下它工作得很好 但是 如果用户单击 UserA UserProfile 活动 gt 然后单击 A 的关注者
  • MDN 示例中不必要使用 calc()?

    我刚刚读了 CSS 函数calc 在 Mozilla 的开发者网络中 第一个例子在本文使用以下 CSS 代码 banner position absolute left calc 40px width calc 100 80px borde
  • 受二次约束的线性目标最大化

    我有一篇论文中的编程公式 想给它一个解决特定问题的工具 作者将其描述为线性规划 LP 实例 但我不确定 公式有点像如下 max x1 x2 x3 s t x1 x3 x4 x5 lt 10 x2 x5 x3 x7 x1 x9 lt 10 我
  • Tensorflow 2.3:AttributeError:“Tensor”对象没有属性“numpy”

    我想加载借用的文本文件here 其中每一行代表一个 json 字符串 如下所示 overall 2 0 verified true reviewTime 02 4 2014 reviewerID A1M117A53LEI8 asin 750
  • Web请求标头的顺序重要吗?

    我正在发出 POST 请求以将图片上传到网站 页面中有一个FileUpload和一个input textBox 在fiddler中我发现页面正在使用Multipart Post请求模式发送一些数据 Content Disposition m
  • CloudWatch 警报:待确认

    我使用 CloudFormation 模板创建了一个 CW 警报 如下所示 MyAlarm Type AWS CloudWatch Alarm DependsOn CodePipelineSNSTopic Properties Action
  • 如何配置nextjs 9和ant design less的兼容性?

    升级后react react dom and nextjs发生此错误 发生构建错误 home lenovo node modules antd lib style index css 7 身体 语法错误 意外的标记 在 Module com
  • ASP.NET 全局错误处理程序中的 WebMethod:如何捕获 AJAX POST 请求中传递的值

    换句话说 使用 HttpContext 我如何检索传递给 WebMethod 什么时候在全局错误处理程序中 Kovu 给出了一个很好的例子如何做一个全局错误陷阱来抓取 WebMethod Global asax 中的错误 我认为他是从那里得
  • 指针变量,var 和 &var 的区别

    include
  • Heroku:将 Rails 应用程序推送到 Heroku 时出错,Heroku 找不到 Rails 应用程序

    我正在尝试将 Rails 应用程序推送到 Heroku 但是我不断收到此错误 user git push heroku master Initializing repository done Counting objects 158 don
  • Python列表理解:列出没有重复项的子项

    我正在尝试打印列表中所有单词中的所有字母 不重复 我试过 gt gt gt wordlist cat dog rabbit gt gt gt letterlist gt gt gt letterlist append x for x in
  • iOS中随机显示字符串而不重复它们

    我正在制作一个测验应用程序 该应用程序使用 json 文件作为问题和答案的 数据库 这个 json 文件如下所示 id 1 question Earth is a answers Planet Meteor Star Asteroid di
  • 访问新窗口 - cypress.io

    问题就这么简单 在 Cypress 中 如何访问运行测试时打开的新窗口 重新创建的步骤 运行测试 进行一些操作后 会弹出新窗口 URL 本质上是动态的 填写新窗口中的字段 然后单击几个按钮 在新窗口中完成所需操作后 关闭新窗口并返回主窗口
  • 如何重写动态对象属性的 get 访问器

    假设我有以下课程 public class Person public string Name get set public string Surname get set public string FullName get return
  • 滚动滞后差异

    好的 我希望在 R 中创建滚动滞后差异 vec lt c 43 79979 44 04865 44 17308 44 54638 44 79524 44 79524 44 79524 44 42195 44 54638 44 79524 4
  • 初始化本地安装的 ESLint 后节点模块消失

    在我最初的反应应用程序中 由react native init project name 在我的项目文件夹中 我通过以下方式在本地安装 ESLintyarn add eslint dev 然后我通过以下方式初始化我的配置 node modu
  • 每日本地通知不起作用

    我的问题是我正在尝试安排每天在特定时间发出的通知 这是我的代码 import SwiftUI struct notifView View var body some View VStack VStack Button Request Per