swift3 - 每周触发通知 Swift 3

标签 swift3 notifications calendar weekday

我正在尝试制定一个时间表,其中我需要记住我类的所有星期,例如特定时间的星期一。问题是,如果我在打印变量 triggerWeekly 时分配 weekday = 1(星期日),它会告诉我 weekday = 2,因此通过执行测试,我不会收到此类通知。我需要知道为什么会这样

let weekday = 1 //Sunday 19 Mar 
let calendar = NSCalendar.current
var date = DateComponents()
date.weekday = weekday
date.hour = 1
date.minute = 5

let ultimateDate = calendar.date(from: date)

let triggerWeekly = Calendar.current.dateComponents([.weekday, .hour, .minute], from:
ultimateDate!)

print(triggerWeekly) // hour: 1 minute: 5 second: 0 weekday: 2 isLeapMonth: false 
let trigger = UNCalendarNotificationTrigger(dateMatching: triggerWeekly, repeats: true)
let identifier = "curso\(String(Index))"
let request = UNNotificationRequest(identifier: identifier,
                                        content: content, trigger: trigger)

最佳答案

您可以将触发器设置为每周一凌晨 1:05 重复,如下所示:

import UserNotifications

let trigger = UNCalendarNotificationTrigger(dateMatching: DateComponents(hour: 1, minute: 5, weekday: 2), repeats: true)
print(trigger.nextTriggerDate() ?? "nil")

let content = UNMutableNotificationContent()
content.title = "title"
content.body = "body"
// make sure you give each request a unique identifier. (nextTriggerDate description)
let request = UNNotificationRequest(identifier: "identify", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request) { error in
    if let error = error {
        print(error)
        return
    }
    print("scheduled")
}

在尝试安排通知之前,不要忘记询问用户安排通知的权限:
UNUserNotificationCenter.current().requestAuthorization(options:[.badge, .alert, .sound]) { granted, error in
    if granted {
        print("authorized")
    }
}

关于swift3 - 每周触发通知 Swift 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42882832/

相关文章:

email - 避免 "add friend"滥用的最佳实践

ios - 迅速3检查计时器是否正在运行

arrays - 在 Swift3 中对数组进行排序

ios - 从 AVAssetExportSession 导出视频时,CATextlayer 字体大小不会改变

ios - 如果用户不打开应用程序而忽略了太多通知,iOS 是否会停止发送静默推送通知?

Excel:基于事件日期的日历翻转效果

ios - 如何清除swift 3中Linkedin的登录 session

visual-studio - Visual Studio 2013 隐藏通知按钮

javascript - React Native 中的完整日历之类的库

java - java中的毫秒计时