UILocalNotification 開發過程當中的使用

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 方法應該不像表面同樣。app

fireDate 
通知將要展現的時間,在沒有展現的時候,notification會存入[UIApplication sharedApplication].scheduledLocalNotifications 列表中, 一經展現,就會從列表中移除。因此理解這個時間很重要orm

已經展現的LocalNotification 怎麼移除?
這邊我目前有兩種方式
1.NSMutableArray 將Notification存入數組,將要移除的時候遍歷
 ```
for (UILocalNotification *noti in localArray)
    {
        NSDictionary *dict = noti.userInfo;
        if ([[dict objectForKey:@"key"] isEqualToString:msgId])
        {
            [app cancelLocalNotification:noti];
        }接口

}
```
2. UILocalNotification 引用須要維護的當前正在顯示的Notification,如例子1: 需求是在通知欄顯示用戶未發送成功的消息數,消失數是往上增長的,但顯示未讀數這類型的通知就一條。這時候想到的最優方法是 顯示一個通知,直接更新通知中的內容,但在實際的嘗試中,並未有這個方法接口,因此只能先刪除當前的Notification,再新建一個Notification。get

相關文章
相關標籤/搜索