在iOS中,可以使用UNUserNotificationCenter类来实现本地通知的触发。为了在随机时间触发本地通知,可以使用DispatchQueue的asyncAfter方法来设置一个随机延迟时间。
下面是一个示例代码,演示了如何在随机时间触发本地通知:
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.scheduleLocalNotification()
} else {
// 用户授权失败
print("用户未授权通知")
}
}
}
func scheduleLocalNotification() {
// 创建通知内容
let content = UNMutableNotificationContent()
content.title = "本地通知"
content.body = "这是一个随机触发的本地通知"
content.sound = UNNotificationSound.default
// 随机延迟时间
let randomDelay = Double.random(in: 1...10) // 1秒到10秒之间的随机延迟
// 创建触发器
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: randomDelay, repeats: false)
// 创建通知请求
let request = UNNotificationRequest(identifier: "randomNotification", content: content, trigger: trigger)
// 添加通知请求到通知中心
UNUserNotificationCenter.current().add(request) { (error) in
if let error = error {
print("添加通知请求失败: \(error.localizedDescription)")
} else {
print("成功添加通知请求")
}
}
}
}
上述代码中,首先在viewDidLoad
方法中请求用户授权通知。如果用户授权成功,则调用scheduleLocalNotification
方法来创建并添加本地通知请求。
在scheduleLocalNotification
方法中,首先创建了通知的内容。然后使用Double.random(in: 1...10)
方法生成一个1到10之间的随机延迟时间。接下来,使用UNTimeIntervalNotificationTrigger
创建一个基于时间间隔的触发器,并将随机延迟时间作为参数传递给触发器。最后,创建一个通知请求,并调用UNUserNotificationCenter.current().add
方法将请求添加到通知中心中。
注意:在使用本地通知之前,需要在应用的Info.plist
文件中添加NSUserNotificationEnabled
键,值设置为YES
,以确保应用具有发送本地通知的权限。