Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS 10 How to view a list of pending notifications using UNUserNotificationCenter?

Solution Code:

let center = UNUserNotificationCenter.current()
print(center.getPendingNotificationRequests(completionHandler: { error in
        // error handling here
    }))

My original post:

I am trying to get a list of pending notifications via UNUserNotificationCenter as UIApplication.shared.scheduledLocalNotifications was depreciated.

This is the code I'm using:

let center = UNUserNotificationCenter.current()
    print(UNUserNotificationCenter.getPendingNotificationRequests(center))

However this prints "(Function)". getPendingNotificationRequests requires a UNUserNotificationCenter parameter and I can't think of what else it could be.

Thanks

like image 814
Ian Kohlert Avatar asked Oct 26 '16 19:10

Ian Kohlert


3 Answers

The getPendingNotificationRequests call passes an array of requests to the completion closure. Try something like this:

let center = UNUserNotificationCenter.current()
center.getPendingNotificationRequests(completionHandler: { requests in
    for request in requests {
        print(request)
    }
})
like image 131
Jerry Avatar answered Nov 09 '22 13:11

Jerry


Just in case anyone needs to access notifications that are already delivered (user can see them in notification center), this can be done in the following way:

    let center = UNUserNotificationCenter.current()
    center.getDeliveredNotifications { notifications in
            // use center.removeDeliveredNotifications(withIdentifiers:requestIdsToRemove)
            // if you want to cancel some of the notifications displayed to user
        }
    }
like image 33
algrid Avatar answered Nov 09 '22 12:11

algrid


it's not actually now, but you should allow to use notifications

UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { (granted, error) in
        if !granted {
            print("user has declined notifications")
        }
    }
like image 1
Колхозник Avatar answered Nov 09 '22 11:11

Колхозник