Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 避免覆盖swift中的本地通知_Ios_Swift_Localnotification - Fatal编程技术网

Ios 避免覆盖swift中的本地通知

Ios 避免覆盖swift中的本地通知,ios,swift,localnotification,Ios,Swift,Localnotification,我使用以下代码创建本地通知,问题是新通知覆盖了上一个通知: let content = UNMutableNotificationContent() content.title = userInfo["title"] as! String content.body = userInfo["message"] as! String content.sound = UNNotificationSound.default() let trigger = UNTimeIntervalNotificat

我使用以下代码创建本地通知,问题是新通知覆盖了上一个通知:

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)

如何避免这种情况?

只需为每个通知设置不同的
标识符:
。每次都会自动创建新的本地通知

请使用以下示例代码随机生成通知标识符。

  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)

在通知标识符中添加时间戳,如下面的代码所示

让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)

我想你需要唯一的标识符