swift 创建多个不同时间自己设置年月日发送的通知
在 Swift 中,我们可以使用 UNUserNotificationCenter 来创建和发送通知。以下是一个示例,演示如何创建多个不同时间的通知:
import UIKit
import UserNotifications
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// 请求通知权限
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { (granted, error) in
if granted {
// 创建并发送通知
self.scheduleNotifications()
}
}
}
func scheduleNotifications() {
let center = UNUserNotificationCenter.current()
// 创建第一个通知
let content1 = UNMutableNotificationContent()
content1.title = "通知1"
content1.body = "这是第一个通知"
content1.sound = .default
let date1 = DateComponents(year: 2022, month: 1, day: 1, hour: 9, minute: 0)
let trigger1 = UNCalendarNotificationTrigger(dateMatching: date1, repeats: false)
let request1 = UNNotificationRequest(identifier: "Notification1", content: content1, trigger: trigger1)
center.add(request1) { (error) in
if let error = error {
print("Failed to schedule notification1:", error)
}
}
// 创建第二个通知
let content2 = UNMutableNotificationContent()
content2.title = "通知2"
content2.body = "这是第二个通知"
content2.sound = .default
let date2 = DateComponents(year: 2022, month: 1, day: 1, hour: 10, minute: 0)
let trigger2 = UNCalendarNotificationTrigger(dateMatching: date2, repeats: false)
let request2 = UNNotificationRequest(identifier: "Notification2", content: content2, trigger: trigger2)
center.add(request2) { (error) in
if let error = error {
print("Failed to schedule notification2:", error)
}
}
// 创建第三个通知
let content3 = UNMutableNotificationContent()
content3.title = "通知3"
content3.body = "这是第三个通知"
content3.sound = .default
let date3 = DateComponents(year: 2022, month: 1, day: 1, hour: 11, minute: 0)
let trigger3 = UNCalendarNotificationTrigger(dateMatching: date3, repeats: false)
let request3 = UNNotificationRequest(identifier: "Notification3", content: content3, trigger: trigger3)
center.add(request3) { (error) in
if let error = error {
print("Failed to schedule notification3:", error)
}
}
}
}
在上面的示例中,我们首先请求通知权限,然后在授权成功后创建并发送通知。在 scheduleNotifications 方法中,我们创建了三个不同的通知。使用 UNMutableNotificationContent 来设置通知的标题、内容和声音。使用 DateComponents 来设置通知的触发时间。最后,我们使用 UNUserNotificationCenter 的 add 方法来将通知请求添加到通知中心中。
请注意,上述代码中的时间是以 24 小时制表示的。如果需要使用 12 小时制,请相应调整时间的值
原文地址: http://www.cveoy.top/t/topic/iYBi 著作权归作者所有。请勿转载和采集!