Отправить несколько уведомлений несколько раз (Swift) - PullRequest
0 голосов
/ 30 мая 2018

У меня есть средство выбора времени и текстовое поле, в котором пользователь вводит время и заголовок, и я хочу отправить локальное уведомление в то время, когда пользователь выбрал.Мой код работает для отправки одного уведомления, но если я добавляю другое уведомление, оно переопределяет первое, а первое не отправляется.Я думаю, что это может быть из-за идентификатора, но не знаю, как это решить.

Вот мой код:

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 Ответ

0 голосов
/ 31 мая 2018

Если вы хотите запланировать ежедневное уведомление?Попробуйте что-то вроде этого

    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")
        }
    }
...