【问题标题】:Retrieving next request date and associated ID for UNNotificationRequest检索 UNNotificationRequest 的下一个请求日期和关联 ID
【发布时间】:2018-04-05 16:12:29
【问题描述】:

更新:

我需要找到下一个通知请求和相关的 ID,所以我最终选择了这个:

    UNUserNotificationCenter.current().getPendingNotificationRequests {
        (requests) in
        var requestDates = [String:Date]()
        for request in requests{
            let requestId = request.identifier
            let trigger = request.trigger as! UNCalendarNotificationTrigger
            let triggerDate = trigger.nextTriggerDate()
            requestDates[requestId] = triggerDate
        }

        let nextRequest = requestDates.min{ a, b in a.value < b.value }
        print(String(describing: nextRequest))

        }

我认为这种方法可能会提供更优雅的解决方案,但正如 Duncan 在下面指出的那样,UNNotificationRequests 无法比较:

requests.min(by: (UNNotificationRequest, UNNotificationRequest) throws -> Bool>)

如果有人有更好的解决方案,请告诉我。

【问题讨论】:

    标签: swift xcode triggers min unnotificationrequest


    【解决方案1】:

    我认为Sequence 有一个min() 函数,用于符合Comparable 协议的对象序列。我不认为UNNotificationRequest 对象具有可比性,因此您不能直接在UNNotificationRequest 对象数组上使用min()

    您必须首先使用 flatMap 将通知数组转换为非零触发日期数组:

    UNUserNotificationCenter.current().getPendingNotificationRequests { requests in
        //map the array of `UNNotificationRequest`s to their 
        //trigger Dates and discard any that don't have a trigger date
        guard let firstTriggerDate = (requests.flatMap { 
           $0.trigger as? UNCalendarNotificationTrigger
           .nextTriggerDate()
        }).min() else { return } 
        print(firstTriggerDate)
    }
    

    (该代码可能需要稍作调整才能使其编译,但这是基本思想。)

    【讨论】:

    • 谢谢,我需要与日期关联的标识符,所以我最终使用 dict 来存储信息并在其上运行 min 方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-28
    • 1970-01-01
    • 2017-02-24
    • 1970-01-01
    • 2018-05-10
    相关资源
    最近更新 更多