iOS 10 Local Notifications not showing

5.3k Views Asked by At

I've been working on setting up local notifications for my app in iOS 10, but when testing in the simulator I found that the notifications would be successfully scheduled, but would never actually appear when the time they were scheduled for came. Here's the code I've been using:

let UNcenter = UNUserNotificationCenter.current()
        UNcenter.requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in
            // Enable or disable features based on authorization

            if granted == true {

                self.testNotification()


            }

        }

Then it runs this code (assume the date/time is in the future):

func testNotification () {
    let date = NSDateComponents()


    date.hour = 16
    date.minute = 06
    date.second = 00
    date.day = 26
    date.month = 1
    date.year = 2017

    let trigger = UNCalendarNotificationTrigger(dateMatching: date as DateComponents, repeats: false)

    let content = UNMutableNotificationContent()
    content.title = "TestTitle"
    content.body = "TestBody"
    content.subtitle = "TestSubtitle"

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

    UNUserNotificationCenter.current().add(request) {(error) in
        if let error = error {
            print("error: \(error)")
        } else {
            print("Scheduled Notification")
        }

    }
}

From this code, it will always print "Scheduled Notification", but when the notification is supposed to be triggered, it never triggers. I've been unable to find any fix for this.

1

There are 1 best solutions below

1
Allen On

Here are a few steps.

  1. Make sure you have the permission. If not, use UNUserNotificationCenter.current().requestAuthorization to get that. Or follow the answer below if you want to show the request pop up more than once.

  2. If you want to show the notification foreground, having to assign UNUserNotificationCenterDelegate to somewhere.

This answer might help.