ios - 有没有更好的方法来检查事件通知设置?

标签 ios swift uilocalnotification

在 Swift 中是否有更好的方法来检查是否在 application.currentUserNotificationSettings().types 上设置了特定标志?

例如,您将如何检查应用程序是否允许更新它的角标(Badge)?

下面是我当前使用的方法,但我认为 Swift 中可能有更好的方法,比如一些我不知道的运算符。

func printUserNotificationSettings() {
    println("Notification Settings:")
    let notificationSettingsTypes = UIApplication.sharedApplication().currentUserNotificationSettings().types
    let badgeOn: Bool = (notificationSettingsTypes & UIUserNotificationType.Badge) == UIUserNotificationType.Badge
    let soundOn: Bool = (notificationSettingsTypes & UIUserNotificationType.Sound) == UIUserNotificationType.Sound
    let alertOn: Bool = (notificationSettingsTypes & UIUserNotificationType.Alert) == UIUserNotificationType.Alert

    println("\tBadge? \(badgeOn)")
    println("\tSound? \(soundOn)")
    println("\tAlert? \(alertOn)")
}

最佳答案

看来要改进代码,唯一可以做的就是使其更加简洁。

func printUserNotificationSettings() {
    println("Notification Settings:")
    let notificationSettingsTypes = UIApplication.sharedApplication().currentUserNotificationSettings().types
    let badgeOn = (notificationSettingsTypes & .Badge) != nil
    let soundOn = (notificationSettingsTypes & .Sound) != nil
    let alertOn = (notificationSettingsTypes & .Alert) != nil

    println("\tBadge? \(badgeOn)")
    println("\tSound? \(soundOn)")
    println("\tAlert? \(alertOn)")
}

UIUserNotificationType 实现了 RawOptionSetType,它是 Objective C 代码中 NS_OPTIONS 的快速映射。在早期的 Xcode 测试版中,这些对象还实现了 BooleanType,这会让您可以更简洁地编写此代码,但似乎在发布之前已将其删除。

另外,四处搜索,最常见的检查方法是 != nil 所以我也包含了那个修改,它似乎提高了一点可读性。

这里有一篇关于该主题的非常强大的 StackOverflow 帖子:Switch statement for imported NS_OPTIONS (RawOptionSetType) in Swift?

还有另一篇关于 RawOptionSetType 背景的精彩文章:http://nshipster.com/rawoptionsettype/

关于ios - 有没有更好的方法来检查事件通知设置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30108395/

相关文章:

ios - 循环遍历字符串数组(迭代图像)

iOS - NavigationItem titleView 在第一次加载时居中,但随后固定在左上角

ios - 注意到场景包中节点位置进入某个边界框了吗?

ios - scheduleLocalNotification 在 Swift 2.0 中不起作用

ios - 在两点 (x1,y1,z1) 到 (x2,y2,z2) 之间画线

ios - 如何最小化 iOS8 "UIVisualEffectView with Blur"的视觉闪烁

Swift Codable 和模型数组

ios - 如何从完成 block 返回值以在其他 viewController 中使用它?

ios - objective-c : how to execute a function when app is in the background/killed automatically based on time Intervals

ios - 是否可以在显示本地通知之前触发 api 调用?