以下是一个使用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.scheduleNotification()
}
}
}
func scheduleNotification() {
// 创建通知内容
let content = UNMutableNotificationContent()
content.title = "本地通知"
content.body = "这是一个立即触发的本地通知"
content.sound = UNNotificationSound.default
// 创建立即触发的触发器
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 0, repeats: false)
// 创建通知请求
let request = UNNotificationRequest(identifier: "ImmediateNotification", content: content, trigger: trigger)
// 添加通知请求到通知中心
UNUserNotificationCenter.current().add(request) { (error) in
if let error = error {
print("添加通知请求错误:\(error.localizedDescription)")
} else {
print("本地通知触发成功")
}
}
}
}
在上述代码中,首先我们请求用户授权通知。如果用户授权,我们会调用scheduleNotification
方法来创建一个本地通知。我们创建了一个立即触发的触发器UNTimeIntervalNotificationTrigger
,并将其时间间隔设置为0,表示立即触发。然后,我们创建一个通知请求,将其添加到通知中心。
请注意,为了能够发送本地通知,您还需要在项目的Info.plist
文件中添加对通知的使用说明。