处理本地通知的最佳方式

时间:2014-07-19 03:48:24

标签: ios notifications uilocalnotification

我有以下问题:

我有2个日历,它们都需要创建本地通知(在每个事件发生前5分钟会触发)。在设置中,用户可以为任一日历打开或关闭通知。如果用户最初使用两个日历的通知,现在只想使用一个日历的通知,那么如何才能删除一个日历中的通知?

我想我有3个选择:

  1. 运行[[UIApplication sharedApplication] cancelAllLocalNotifications];,然后将其他日历中的所有内容添加回来(这可能比听起来更难)。
  2. 将创建的通知数组存储在用户默认值之类的内容中,然后循环调用数组:[[UIApplication sharedApplication] cancelLocalNotification:notification];
  3. UILocalNotification进行子类化并添加一些允许我对通知进行排序的字段。然后也许我可以调用[[UIApplication sharedApplication] scheduledLocalNotifications]并循环检查该字段并删除那些必要的字段。
  4. 有没有一种标准的方法可以做到这一点?我认为第三个可能是最简单的,但我不确定它是否会起作用。

1 个答案:

答案 0 :(得分:0)

UILocalNotification具有标准userInfo属性,只要键是有效的属性列表类型,就是NSDictionary任意值。如果您继承UILocalNotification,则必须将该字典用作后续存储,以用于您希望保留的其他属性或字段。为了能够使用您的子类,您将需要一个初始化方法,该方法将属性从基类复制到您的子类。

#define kNoficationCalendarName NSStringFromSelector(@selector(calendarName))

@interface XXLocalNotification : UILocalNotification

@property (nonatomic, strong) NSString * calendarName;

- (instancetype)initWithLocalNotification:(UILocalNotification *)notification;

@end

@implementation XXLocalNotification

- (instancetype)initWithLocalNotification:(UILocalNotification *)notification
{
    self = [super init];
    if (self)
    {
        //Copy properties
        self.alertAction = notification.alertAction;
        self.alertBody = notification.alertBody;
        self.alertLaunchImage = notification.alertLaunchImage;
        self.applicationIconBadgeNumber = notification.applicationIconBadgeNumber;
        self.fireDate = notification.fireDate;
        self.hasAction = notification.hasAction;
        self.repeatCalendar = notification.repeatCalendar;
        self.repeatInterval = notification.repeatInterval;
        self.soundName = notification.soundName;
        self.timeZone = notification.timeZone;
        self.userInfo = notification.userInfo;
    }
    return self;
}
-(void)setCalendarName:(NSString *)calendarName
{
    NSMutableDictionary * userInfo = [[self userInfo] mutableCopy];
    [userInfo setValue:calendarName
                forKey:kNoficationCalendarName];
}
- (NSString *)calendarName
{
    return [[self userInfo] valueForKey:kNoficationCalendarName];
}

@end
相关问题