【问题标题】:Count pending local notifications计算待处理的本地通知
【发布时间】:2017-07-18 20:03:03
【问题描述】:

我正在尝试编写一个函数来检查我是否已达到 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 的初始值。

我尝试过的其他方法。

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

【问题讨论】:

    标签: ios swift localnotification


    【解决方案1】:

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

    由于 getPendingNotificationRequests 闭包中有延迟,因此您的函数首先打印 false。

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-09-16
      • 2020-05-18
      • 2013-02-03
      • 2019-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多