多次发送多个通知 (Swift)

Posted

技术标签:

【中文标题】多次发送多个通知 (Swift)【英文标题】:Send Multiple Notifications at Multiple Times (Swift) 【发布时间】:2018-05-30 17:53:24 【问题描述】:

我有一个时间选择器和一个文本字段,用户可以在其中输入时间和标题,我想在用户选择的时间发送本地通知。我的代码可以发送一个通知,但是如果我添加另一个通知,它会覆盖第一个通知,并且不会发送第一个通知。我认为这可能是因为标识符,但不知道如何解决。

这是我的代码:

let calendar = Calendar.current

let datec = Date()

let hour = Calendar.current.component(.hour, from: StartTimePicker.date)
let minute = Calendar.current.component(.minute, from: StartTimePicker.date)

let year = calendar.component(.year, from: datec)
let month = calendar.component(.month, from: datec)
let day = calendar.component(.day, from: datec)


let components = DateComponents(year: year, month: month, day: day, hour: hour, minute: minute) // Set the date here when you want Notification
let date = calendar.date(from: components)
let comp2 = calendar.dateComponents([.year,.month,.day,.hour,.minute], from: date!)
let trigger = UNCalendarNotificationTrigger(dateMatching: comp2, repeats: true)

let content = UNMutableNotificationContent()
content.title = "Schedule Alert"
content.body = TitleTextField.text! + " from " + time

let request = UNNotificationRequest(
    identifier: "identifier",
    content: content,
    trigger: trigger
)

UNUserNotificationCenter.current().add(request, withCompletionHandler:  error in
    if error != nil 
        //handle error
     else 
        //notification set up successfully
    

【问题讨论】:

如果您希望通知是唯一的,请为每个通知创建一个唯一标识符 【参考方案1】:

如果您想安排每日通知?试试这样的

    let content = UNMutableNotificationContent.init()
    content.title = "Schedule Alert"
    content.body = TitleTextField.text!

    // Add a sound and a badge
    content.sound = UNNotificationSound.default()
    content.badge = 1

    // Create a unique identifier
    let identifier = UUID.init().uuidString

    // Date components for daily notifications
    var dateComponents = Calendar.current.dateComponents([.hour, .minute], from: StartTimePicker.date)
    dateComponents.second = 0

    let trigger = UNCalendarNotificationTrigger.init(dateMatching: dateComponents, repeats: true)
    let request = UNNotificationRequest.init(identifier: identifier, content: content, trigger: trigger)

    let center = UNUserNotificationCenter.current()
    center.add(request)  (error) in
        if error != nil 
            print("Failed")
         else 
            print("Success")
        
    

【讨论】:

以上是关于多次发送多个通知 (Swift)的主要内容,如果未能解决你的问题,请参考以下文章

推送通知在android中获得多次

Swift:多个本地通知,但只显示最新的

我不能在 Swift 中调用多个应用程序消息

多线程与通知

多线程与通知

多线程与通知