【问题标题】:Daily local notification on iOSiOS 上的每日本地通知
【发布时间】:2017-07-11 12:42:05
【问题描述】:

我需要在每天 19:30 发出本地通知提醒用户。

这是我所做的:

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

    let identifier = "daily.alarm"
    let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)

    UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
    UNUserNotificationCenter.current().add(request, withCompletionHandler: { (error) in
      if error != nil {
        debugPrint("center.add(request, withCompletionHandler: { (error)")
      } 
    })

但是,我发现通知在 19:30 时没有提醒。相反,它会提前 15 分钟发出警报。此外,它也不能每天报警。我做错了什么?

【问题讨论】:

    标签: ios unnotificationrequest unnotificationtrigger


    【解决方案1】:

    使用以下功能安排您的通知:

    func registerLocal() {
        let center = UNUserNotificationCenter.current()
    
        center.requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in
            if granted {
                print("Yas!")
            } else {
                print("Ohhh No!!")
            }
        }
    }
    
    func scheduleLocal() {
        let center = UNUserNotificationCenter.current()
    
        let content = UNMutableNotificationContent()
        content.title = "Drink Milk"
        content.body = "Two Servings A Day Keeps Bone Problems At Bay."
        content.categoryIdentifier = "alarm"
        content.userInfo = ["customData": "whater"]
        content.sound = UNNotificationSound.default()
    
        var dateComponents = DateComponents()
        dateComponents.hour = 19
        dateComponents.minute = 30
    
        let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)
    
        let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
        center.add(request)
    }
    

    【讨论】:

    • 我已经完成了 registerLocal() 函数,只是我没有在这里发布它,因为它不是重点。上面的代码仍然不会在每天 1930 触发警报。
    • 你的测试如何@user6539552
    • 第一次报警没问题,但不会重复!!
    • 如果我要安排两个通知,它们具有不同的标识符和内容。我使用了代码 UNUserNotificationCenter.current().removeAllPendingNotificationRequests() 这会删除彼此的待处理通知吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多