您可以使用以下代码,在显示通知后计算下一个最后一天月份。
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge])
{ (granted, error) in
// Enable or disable features based on authorization
}
let current = UNUserNotificationCenter.current()
current.delegate = self
setNotificationRequest()
}
func setNotificationRequest(offset: Int = 0) {
let content = UNMutableNotificationContent()
content.title = "Alarm"
content.body = "Alarm for End of Month"
content.sound = UNNotificationSound.default
var dateCompo = DateComponents()
dateCompo.day = lastDay(offset: offset)
let trigger = UNCalendarNotificationTrigger.init(dateMatching: dateCompo, repeats: true)
let request = UNNotificationRequest(identifier: "alarm-id", content: content, trigger: trigger)
UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
UNUserNotificationCenter.current().add(request)
}
func lastDay(offset: Int) -> Int {
let cal = Calendar.current
let m = cal.component(.month, from: Date()) + 1
let y = cal.component(.year, from: Date())
var comps = DateComponents(calendar: cal, year: y, month: m)
comps.setValue(m + 1, for: .month)
comps.setValue(0, for: .day)
let date = cal.date(from: comps)!
return cal.component(.day, from: date)
} }
extension ViewController: UNUserNotificationCenterDelegate {
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
// offset is set to 1 as we want to get last of next month now.
setNotificationRequest(offset: 1)
completionHandler([.badge, .sound])
} }
我已经测试过了,对我来说工作正常。