swift - 为 UNNotificationRequest 检索下一个请求日期和关联的 ID

标签 swift xcode triggers min unnotificationrequest

更新:

我需要找到下一个通知请求和关联的 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>)

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

最佳答案

我认为 Sequence 有一个 min() 函数,用于符合 Comparable 协议(protocol)的对象序列。我不认为 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)
}

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

关于swift - 为 UNNotificationRequest 检索下一个请求日期和关联的 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49676957/

相关文章:

ios - 如何在核心数据中保存图像

swift - UITableView 未显示正确的行数

xcode - Swift 版本 1.2 在 Xcode 6.3 的 Playground 中不可用?

mysql - 如何确保插入 SQL View 的行将是该 View 的元素?

swift - 可重用的 UICollectionViewCell 不更改 UIImageView 属性(显示重复项)

swift - CIFilter CISmoothLinearGradient 在 Swift 中传递颜色时崩溃

ios - 当键盘出现时,快速 UITableView 向上滚动,但我看不到顶部单元格

xcode - iCloud 设置和配置

mariadb 中的 mysql 触发器语法错误

wpf - 触发器和数据触发器有什么区别?