避免在swift中覆盖本地通知

loading...


0

我使用下面的代码来创建本地通知,问题是最后一个新通知覆盖:

let content = UNMutableNotificationContent()
content.title = userInfo["title"] as! String
content.body = userInfo["message"] as! String
content.sound = UNNotificationSound.default()

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

UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)

我怎么能避免这个?

loading...

2回答

  • 0

    只需为每个通知设置不同的 identifier: . 它会每次自动创建新的本地通知 .

    Please use below sample code for generate notification identifier randomly.

    extension NSObject {
        func randomNumber() -> Int {
                let randomNumber = Int(arc4random_uniform(UInt32(INT_MAX)))
                return randomNumber
            }
        }
    

    现在,使用以下代码创建本地通知 .

    let content = UNMutableNotificationContent()
    content.title = userInfo["title"] as! String
    content.body = userInfo["message"] as! String
    content.sound = UNNotificationSound.default()
    
    //Random notification ID
    let identifier = "HS\(String(self.randomNumber()))"
    
    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
    let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)
    UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
    

  • 0

    在通知标识符中添加时间戳,例如按照此代码 .

    let timestamp = NSDate().timeIntervalSince1970

    let content = UNMutableNotificationContent()
    content.title = userInfo["title"] as! String
    content.body = userInfo["message"] as! String
    content.sound = UNNotificationSound.default()
    
    let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
    let timestamp = NSDate().timeIntervalSince1970
    let request = UNNotificationRequest(identifier: "TestIdentifier\(Int(timestamp))", content: content, trigger: trigger)
    
    UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
    
评论

暂时没有评论!