Search code examples
iosswiftlocalnotification

Count pending local notifications


I am tryin to write a function to check if I have reached the limit of 64 local notifications. There are some answers out there to deal with UIlocalNotifications but I am yet to find one for NSlocalNotifications. Here is my function

     func notificationLimitreached()  {
    let center = UNUserNotificationCenter.current()
    var limit = false
    center.getPendingNotificationRequests(completionHandler: { requests in
        print(requests.count)
        if requests.count > 59 {
            limit = true
            print(limit)
        } else {
            limit = false
        }

    })
    print (limit)

problem is the "limit" variable prints true when inside the closure and then resets to initialized value of false after leaving closure.

Something else I have tried.

-- setting global variables when inside closure again as soon as I read this value else where its set to its original value


Solution

  • As you can see you're facing async logic:

    Your function prints false first because there's delay within getPendingNotificationRequests closure.

    Try this function and see if that works:

    func isNotificationLimitreached(completed: @escaping (Bool)-> Void = {_ in }) {
        let center = UNUserNotificationCenter.current()
        center.getPendingNotificationRequests(completionHandler: { requests in
    
            completed(requests.count > 59)
        })
    }
    

    And you can call this function with following code:

        isNotificationLimitreached { isReached in
            print(isReached)
        }