有没有办法在Swift中立即传递本地通知?

and*_*dre 0 iphone notifications swift ios12

我有一个函数,想要在执行该函数时传递本地通知。目前,我一直在使用“时间间隔通知”触发器,并将时间间隔设置为0.1s,但这似乎不是立即传递通知的正确方法,因为它仍然有0.1s的延迟,即使它几乎没有引起注意。 。

我的问题是,是否可以像没有任何延迟一样立即发送通知?我一直在寻找解决这个问题的方法,但是还没有找到任何方法,希望你们能提供帮助。谢谢。

func didUpdateSettings() {
    //other code...
    let content = UNMutableNotificationContent()

    content.title = "Notification title"
    content.subtitle = "Notification subtitle"
    content.body = "Notification body"
    content.sound = UNNotificationSound.default

    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 0.1, repeats: false)
    let request = UNNotificationRequest(identifier: "timerDone", content: content, trigger: trigger)

    UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
}
Run Code Online (Sandbox Code Playgroud)

alx*_*ves 8

根据文档:

https://developer.apple.com/documentation/usernotifications/unnotificationrequest/1649633-init

触发器导致传递通知的条件。指定nil立即发送通知。

因此,代码将是:

let request = UNNotificationRequest(identifier: "timerDone", content: content, trigger: nil)
Run Code Online (Sandbox Code Playgroud)