Jonathan Divens
Jonathan Divens

Reputation: 23

Run multiple notifications through a function in Swift in Xcode?

I've created a function which will send the user a notification at a specific hour and minute with specified text. The problem is, when I call the function twice (trying to send two notifications), it only runs the second notification. Essentially, I need to be able to call the function multiple times to get multiple notifications at different times. My guess is calling it a second time overwrites the prior. Anyway I can fix/accomplish this? Here's my code:

func notification(hour: Int, minute: Int, text: String){

    let content = UNMutableNotificationContent()
    content.title = "Example"
    content.body = text
    content.sound = UNNotificationSound.default()

    var date = DateComponents()
    date.hour = hour
    date.minute = minute
    let trigger = UNCalendarNotificationTrigger(dateMatching: date, repeats: true)

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

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

}

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    notification(hour: 12, minute: 5, text: "It is 12:05.")
    notification(hour: 12, minute: 10, text: "It is 12:10.")

}

Upvotes: 1

Views: 634

Answers (1)

Shehata Gamal
Shehata Gamal

Reputation: 100523

It's because the same identifier

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

so change it for every scheduled notification

Upvotes: 1

Related Questions