簡體   English   中英

如何立即彈出UNNotificationRequest?

[英]How can I make UNNotificationRequest pop immediately?

我正在使用UNNotificationRequest ,我希望在單擊按鈕時立即彈出通知。 但在這種情況下,它會在我退出應用程序時出現。 這是我的代碼

@IBAction func shortNotifBtn(_ sender: Any) {
    let center = UNUserNotificationCenter.current()
    let content = UNMutableNotificationContent()
    content.title = "Late wake up call"
    content.body = "The early bird catches the worm, but the second mouse gets the cheese."
    content.categoryIdentifier = "alarm"
    content.userInfo = ["customData": "fizzbuzz"]
    content.sound = UNNotificationSound.default()
    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
    let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
    center.add(request)
}

Max的回答是已過時的UILocalNotification當問題是關於更現代UNNotificationRequest

正確的答案是通過nil 根據UNNotificationRequestrequestWithIdentifier:content:trigger:

trigger

導致通知傳遞的條件。 指定nil立即發送通知。

所以在你的代碼中:

let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: nil)

https://developer.apple.com/reference/uikit/uilocalnotification

如果應用程序在系統發送通知時最重要且可見,則會調用應用程序委托的應用程序(_:didReceive :)來處理通知。 使用提供的UILocalNotification對象中的信息來確定要采取的操作。 當應用程序已經位於最前端時,系統不會顯示任何警報,標記應用程序的圖標或播放任何聲音。

這是正常的行為。 此外,為什么你需要通過點擊按鈕觸發本地通知? 為什么不在點擊按鈕而不通知通知時實現所需的功能?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM