我正在尝试编写一些代码,允许用户设置自定义本地通知以提醒他们一些任务。 我正在使用用户通知框架。 所以基本上用户可以决定设置一个通知,提醒他每周买一些肥皂或每年许生日愿望或每月检查一些东西(这些只是示例)。
到目前为止,我已经能够设置没有重复间隔的本地通知。
func scheduleNotif() {
let dateformatter = DateFormatter()
dateformatter.dateStyle = DateFormatter.Style.medium
dateformatter.timeStyle = DateFormatter.Style.short
let dateFromString = dateformatter.date(from: selectDateTextField.text!)
let fireDateOfNotification: Date = dateFromString!
//if notif are allowed
let content = UNMutableNotificationContent()
content.title = notifTitleTextField.text!
content.body = notifNoteTextView.text
content.sound = UNNotificationSound.default()
content.badge = UIApplication.shared.applicationIconBadgeNumber + 1 as NSNumber
let triggerDate = Calendar.current.dateComponents([.year,.month,.day,.hour,.minute,.second,], from: fireDateOfNotification)
let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDate,
repeats: false)
//Schedule the Notification
let titleNospace = notifTitleTextField.text?.replacingOccurrences(of: " ", with: "")
let identifier = titleNospace
let request = UNNotificationRequest(identifier: identifier!, content: content, trigger: trigger)
self.center.add(request, withCompletionHandler: { (error) in
if let error = error {
print(error.localizedDescription)
}
})
}
日期是从日期选择器中选择的。 现在,我希望用户从另一个选择器中选择重复间隔(无、每日、每周、每月、每年和特定日期)。 我不知道如何才能实现这一目标。我需要使用 if else if 语句吗? (对我来说这似乎不太正确。) 有更好的方法来实现这一目标吗? 谢谢!
最佳答案
目前我已经这样解决了:
let dateformatter = DateFormatter()
dateformatter.dateStyle = .medium
dateformatter.timeStyle = .short
let dateFromString = dateformatter.date(from: selectDateTextField.text!)
let fireDateOfNotification: Date = dateFromString!
var trigger: UNCalendarNotificationTrigger
var triggerDate: DateComponents
var repeatInterval = Bool()
if repeatingInterval == "Hourly" {
triggerDate = Calendar.current.dateComponents([.minute], from: fireDateOfNotification)
repeatInterval = true
} else if repeatingInterval == "Daily" {
triggerDate = Calendar.current.dateComponents([.hour, .minute], from: fireDateOfNotification)
repeatInterval = true
} else if repeatingInterval == "Weekly" {
triggerDate = Calendar.current.dateComponents([.weekday, .hour, .minute], from: fireDateOfNotification)
repeatInterval = true
} else if repeatingInterval == "Monthly" {
triggerDate = Calendar.current.dateComponents([.day, .hour, .minute], from: fireDateOfNotification)
repeatInterval = true
} else if repeatingInterval == "Yearly" {
triggerDate = Calendar.current.dateComponents([.month, .day, .hour, .minute], from: fireDateOfNotification)
repeatInterval = true
} else {
triggerDate = Calendar.current.dateComponents([.year,.month,.day,.hour,.minute,.second,], from: fireDateOfNotification)
repeatInterval = false
}
trigger = UNCalendarNotificationTrigger(dateMatching: triggerDate, repeats: repeatInterval)
//Schedule the Notification
......
尚未找到一种方法来安排不同的时间间隔(例如每两周、每两天、每六个月等)。 我还是会调查一下。 :)
关于ios - 用户选择的 swift 3 重复间隔内的本地通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46001580/