我遇到Local Notification
的问题,我有UIDatePicker
来设置通知时间,还有ViewController
来选择要重复通知的日期。如果我选择每个星期五重复一次,那将是行不通的,或者是另一天。但是,每天的通知运行良好。
我的代码:
func createRequestNotifications() {
let content = UNMutableNotificationContent()
content.title = "Time to learn"
content.body = "Hey bro time to get some knolage)"
content.sound = UNNotificationSound.default()
let gregorian = Calendar(identifier: .gregorian)
let now = Date()
var components = gregorian.dateComponents([.year, .month, .day, .hour, .minute, .second], from: now)
print(notification.day)
components.hour = notifTime
components.minute = notifMin
components.second = 0
components.day = notification.day
components.weekdayOrdinal = 10
components.timeZone = .current
let date = gregorian.date(from: components)!
if notification.day == 0 {
let triggerDaily = Calendar.current.dateComponents([.hour,.minute,.second,], from: date)
let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDaily, repeats: true)
let request = UNNotificationRequest(identifier: "any", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
print("evry day")
} else {
let triggerDaily = Calendar.current.dateComponents([.hour,.minute,.second, .day,], from: date)
let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDaily, repeats: true)
let request = UNNotificationRequest(identifier: "any", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
print("date setup")
}
}
notification.day
是从另一个ViewController
设置的Int值,我选择在其中重复一天。
我很累,因为我不知道问题出在哪里,对于每个日期通知都有效,但是对于特殊的日子,:(
答案 0 :(得分:0)
对于特定日期,您可以设置通知,请参阅以下链接 https://stackoverflow.com/a/46094544/5069429 根据您必须单独设置特定日期的通知 您可以使用这样的功能
func setNotificationFor(weekday:Int,hour:Int,minute:Int,title:String,subTitle:String,body:String){
let notification = UNMutableNotificationContent()
notification.title = title
notification.subtitle = subTitle
notification.body = body
var dateComponents = DateComponents()
dateComponents.weekday = weekday // 0,1,2,3,4,5,6
dateComponents.hour = hour
dateComponents.minute = minute
let notificationTrigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)
let request = UNNotificationRequest(identifier: "notification1", content: notification, trigger: notificationTrigger)
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
}