我需要在特定的时间和特定的日子重复local notification
,例如在星期日和星期五或选定的工作日(周一和周六)上午10:30。
switch repeatDays {
case .never:
dateComponents = Calendar.current.dateComponents([.hour, .minute], from: date)
flag = false
case .everyDay:
dateComponents = Calendar.current.dateComponents([.hour, .minute], from: date)
case .everyWeek:
dateComponents = Calendar.current.dateComponents([.weekday, .hour, .minute], from: date)
case .everyMonth:
dateComponents = Calendar.current.dateComponents([.day, .hour, .minute], from: date)
case .everyYear:
dateComponents = Calendar.current.dateComponents([.month, .day, .hour, .minute], from: date)
}
let notificationTrigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: flag)
let request = UNNotificationRequest(identifier: uuid, content: content, trigger: notificationTrigger)
let notiCurrent = UNUserNotificationCenter.current()
notiCurrent.add(request) { (error) in
if let error1 = error {
print(error1.localizedDescription)
}
}
但是每周一次的重复通知不会重复Sunday
和Wednesday
或其他某些特定日期
答案 0 :(得分:0)
let calendar = Calendar.current
let components = DateComponents(year: 2018, month: 05, day: 06, hour: 20, minute: 22) // Set the date here when you want Notification
let date = calendar.date(from: components)
let comp2 = calendar.dateComponents([.year,.month,.day,.hour,.minute], from: date!)
let trigger = UNCalendarNotificationTrigger(dateMatching: comp2, repeats: true)
let content = UNMutableNotificationContent()
content.title = "Notification Demo"
content.subtitle = "Demo"
content.body = "Notification on specific date!!"
let request = UNNotificationRequest(
identifier: "identifier",
content: content,
trigger: trigger
)
UNUserNotificationCenter.current().add(request, withCompletionHandler: { error in
if error != nil {
//handle error
} else {
//notification set up successfully
}
})
答案 1 :(得分:0)
func scheduleNotification(date:Date, body: String, titles : String) {
let trigger = UNTimeIntervalNotificationTrigger(
timeInterval: 1.0,
repeats: true)
let content = UNMutableNotificationContent()
content.title = body
content.body = titles
content.sound = UNNotificationSound.default()
content.categoryIdentifier = "todoList"
content.setValue("YES", forKeyPath: "shouldAlwaysAlertWhileAppIsForeground") //Update is here
let request = UNNotificationRequest(identifier: "textNotification", content: content, trigger: trigger)
UNUserNotificationCenter.current().delegate = self
UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
UNUserNotificationCenter.current().add(request) {(error) in
if let error = error {
print(" We had an error: \(error)")
}
}
}