22

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

Ian Kohlert
  • 484
  • 1
  • 4
  • 15
  • 1
    Call that function on `center`, not on the class and provide a callback handler https://developer.apple.com/reference/usernotifications/unusernotificationcenter/1649513-getpendingnotificationrequests – Paulw11 Oct 26 '16 at 19:32
  • 1
    Can you mark my answer as accepted? – Jerry Jan 27 '20 at 17:06
  • First make sure you've authorization, then you can schedule notification. – Idan Moshe Oct 05 '20 at 10:41

4 Answers4

47

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)
    }
})
Jerry
  • 4,382
  • 2
  • 35
  • 29
4

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
        }
    }
algrid
  • 5,600
  • 3
  • 34
  • 37
0

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

For ObjC:- [[UNUserNotificationCenter currentNotificationCenter] getPendingNotificationRequestsWithCompletionHandler:^(NSArray<UNNotificationRequest*> *requests){ NSLog(@"requests: %@", requests); }];

praveen
  • 226
  • 2
  • 5