计算待处理的本地通知

Count pending local notifications

我正在尝试编写一个函数来检查我是否已达到 64 个本地通知的限制。有一些处理 UIlocalNotifications 的答案,但我还没有找到 NSlocalNotifications 的答案。这是我的功能

     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)

问题是 "limit" 变量在闭包内时打印 true,然后在离开闭包后重置为 false 的初始化值。

我试过的其他方法。

-- 当我读取此值时再次在闭包内设置全局变量,否则将其设置为原始值

如您所见,您面临的是异步逻辑:

您的函数首先打印 false,因为 getPendingNotificationRequests 闭包中存在延迟。

试试这个功能,看看是否有效:

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

        completed(requests.count > 59)
    })
}

您可以使用以下代码调用此函数:

    isNotificationLimitreached { isReached in
        print(isReached)
    }