在 Swift 中安排本地通知从明天开始每天重复 [英] Scheduling local notifications to repeat daily from tomorrow in Swift

查看:27
本文介绍了在 Swift 中安排本地通知从明天开始每天重复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试安排本地通知每天(即重复)在特定时间触发,但从明天开始.

I'm trying to schedule a local notification to fire every day (i.e. repeats), at a specific time, but from tomorrow.

即从明天开始,每天晚上 8 点触发通知"

i.e "Trigger a notifcation every day at 8pm, from tomorrow"

我一直在使用 this SO question as指导,我相信我正在做它所说的,但是当我运行以下代码时,我今天仍然收到通知(例如,如果我在晚上 8 点之前安排通知):

I've been using this SO question as guidance, and I believe I am doing what it says but I am still getting a notification today when I run the following code (if I schedule the notification before 8pm for instance):

    func testDateNotification(){

    let content = UNMutableNotificationContent()
    content.title = "Test"
    content.body = "This is a test"
    let tomorrow = Calendar.current.date(byAdding: .day, value: 1, to: Date())

    let userCalendar = Calendar.current
    var components = userCalendar.dateComponents([.hour, .minute], from: tomorrow!)

    components.hour = 20
    components.minute = 00


    let trigger = UNCalendarNotificationTrigger(dateMatching: components, repeats: true)
    let request = UNNotificationRequest(identifier: "test", content: content, trigger: trigger)

    UNUserNotificationCenter.current().add(request) { (error) in
        if ((error) != nil){
            print("Error \(String(describing: error))")
        }
    }

}

推荐答案

import UserNotifications

  1. 检查用户权限

  1. Check for user permission

UNUserNotificationCenter.current().requestAuthorization(options:[.badge, .alert, .sound]) {
if $0 { } }

  • 添加通知

  • Add notification

     let fromDate = Date(timeIntervalSince1970: Double(0.0))
    
     let dateComponent = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute, .second], from: fromDate)
    
     let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponent, repeats: true)
     print(trigger.nextTriggerDate() ?? "nil")
    
     let content = UNMutableNotificationContent()
     content.title = "title"
     content.body = "body"
     let request = UNNotificationRequest(identifier: "identify", content: content, trigger: trigger)
     UNUserNotificationCenter.current().add(request) { 
         if let error = $0 {
             print(error)
             return
         }else { 
             print("scheduled") 
         }
     }
    

  • 这篇关于在 Swift 中安排本地通知从明天开始每天重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆