美文网首页iOS学习开发
UILocalNotification 开发过程中的使用

UILocalNotification 开发过程中的使用

作者: wesk痕 | 来源:发表于2016-11-01 14:18 被阅读0次

UILocalNotification
基本创建:方法
例子1:

UILocalNotification *unSendNotification = [[UILocalNotification alloc] init];
unSendNotification.soundName = [self getLocalPushSound];
unSendNotification.category = @"unSendAlert";
unSendNotification.fireDate = [NSDate dateWithTimeIntervalSinceNow:0];
unSendNotification.alertBody = [NSString stringWithFormat:@“%@条消息未发送成功",@(self.unSendMessageIds.count)];

unSendNotification.userInfo = @{@"MsgId":message.msgId};
[[UIApplication sharedApplication] scheduleLocalNotification:unSendNotification];

- (void)presentLocalNotificationNow:(UILocalNotification *)notification; 

立即弹出Push fireDate不需要设置
这个主要运用在app处于后台,收到服务器消息并需要告知用户,这时候用presentLocalNotificationNow: 可以立即弹出通知。

- (void)cancelLocalNotification:(UILocalNotification *)notification; //取消某一个通知

使用时必须要确保要被移除的notification 存在,否则没有效果。
scheduledLocalNotifications // 获取app的本地将要显示的所有LocalNotification 未展示的LocalNotification
[[UIApplication sharedApplication] setApplicationIconBadgeNumber:0]; // 设置app消息未读数为0

/***移除所有通知      但是有时候遇到奇怪的现象,即使调用了以上这个方法 通知还没有移除完,网上搜索了下资料,也有人遇到这种情况。最后使用如下方法可避免。***/
 - (void)cancelAllLocalNotifications; 
{
            [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
 //     [[UIApplication sharedApplication] cancelAllLocalNotifications]; //用这个方法有时候移除不完
            CCLog(@"scheduledLocalNotifications.count :::%ld",[UIApplication sharedApplication].scheduledLocalNotifications.count);
            [UIApplication sharedApplication].scheduledLocalNotifications = nil;
    NSArray *notif = [UIApplication sharedApplication].scheduledLocalNotifications;
            CCLog(@"notif.count :::%ld",notif.count);
}

在[UIApplication sharedApplication].scheduledLocalNotifications获取为空的时候 调用

[UIApplication sharedApplication].scheduledLocalNotifications = nil;

竟然把本地已经展示的LocalNotification 清空了。这里可以看出scheduledLocalNotifications的setter 方法应该不像表面一样。

fireDate
通知将要展示的时间,在没有展示的时候,notification会存入[UIApplication sharedApplication].scheduledLocalNotifications 列表中, 一经展示,就会从列表中移除。所以理解这个时间很重要

已经展示的LocalNotification 怎么移除?
这边我目前有两种方式
1.NSMutableArray 将Notification存入数组,将要移除的时候遍历

for (UILocalNotification *noti in localArray)
   {
       NSDictionary *dict = noti.userInfo;
       if ([[dict objectForKey:@"key"] isEqualToString:msgId])
       {
           [app cancelLocalNotification:noti];
       }

}
  1. UILocalNotification 引用需要维护的当前正在显示的Notification,如例子1: 需求是在通知栏显示用户未发送成功的消息数,消失数是往上增加的,但显示未读数这类型的通知就一条。这时候想到的最优方法是 显示一个通知,直接更新通知中的内容,但在实际的尝试中,并未有这个方法接口,所以只能先删除当前的Notification,再新建一个Notification。

相关文章

网友评论

    本文标题:UILocalNotification 开发过程中的使用

    本文链接:https://www.haomeiwen.com/subject/pwemuttx.html