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/53022412/

相关文章:

swift - swift3中的字符串变量比较

ios - 没有在自定义 UISearchBar 中获取过滤器数据

ios - 调用重复定时器中的方法

asp.net - ASP.Net Calendar 控件中默认选择当前日期

javascript - 如何在 TUI 日历中禁用设置随机日程顺序

ios - Alamofire 读取 header 响应

ios - 在 CollectionView 中的单元格之间拖放不起作用,iOS、PanGestureRecognizer 和 Swift3

algorithm - 识别具有相同星期几的年份(例如 1994、2005、2011)

delphi - 如何捕获 TTN_LINKCLICK 通知?

android - Android中 "Notification"和 "Push Notification"有什么区别