本地通知簡(jiǎn)介:
本地通知簡(jiǎn)單來說app本身給應(yīng)用程序推送消息阁苞,不需要服務(wù)器支持尚卫。使用場(chǎng)景:鬧鐘喧伞,定時(shí)操作窟她。
1.創(chuàng)建本地通知
//? 創(chuàng)建本地通知對(duì)象
UILocalNotification *localNoti = [[UILocalNotification alloc] init];
2.設(shè)置本地通知屬性
NSDateFormatter *date_formatter = [[NSDateFormatter alloc] init];
[date_formatter setDateFormat:@"yyyy-MM-dd"];
NSString *TimeStr = [date_formatter stringFromDate:[NSDate date]];
/** 目前是定時(shí)每天九點(diǎn),后續(xù)版本迭代在封裝 */
TimeStr = [NSString stringWithFormat:@"%@ 09:00:00",TimeStr];
[date_formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDate *dateTime = [date_formatter dateFromString:TimeStr];
//1.設(shè)置推送類型
UIUserNotificationType type = UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert;
//2.設(shè)置setting
UIUserNotificationSettings *setting? = [UIUserNotificationSettings settingsForTypes:type categories:nil];
//3.主動(dòng)授權(quán)
[[UIApplication sharedApplication] registerUserNotificationSettings:setting];
//時(shí)區(qū)
localNoti.timeZone = [NSTimeZone defaultTimeZone];
//時(shí)間
localNoti.fireDate = dateTime;
//重復(fù)間隔
localNoti.repeatInterval = kCFCalendarUnitDay;
//通知內(nèi)容
localNoti.alertBody = @"今日活動(dòng)任務(wù)有到期";
//通知聲音
localNoti.soundName = UILocalNotificationDefaultSoundName;
//? ? //通知參數(shù)
//? ? localNoti.userInfo = [NSDictionary dictionaryWithObject:@"NotificationStr" forKey:@"Notification"];
//發(fā)送通知:
[[UIApplication sharedApplication] scheduleLocalNotification:localNoti];
3.取消通知
#pragma mark -- 取消通知
- (void)cancelLocalNotification
{
// 獲取所有本地通知數(shù)組
NSArray *localNotifications = [UIApplication sharedApplication].scheduledLocalNotifications;
for (UILocalNotification *notification in localNotifications) {
NSDictionary *userInfo = notification.userInfo;
if (userInfo) {
// 根據(jù)設(shè)置通知參數(shù)時(shí)指定的key來獲取通知參數(shù)
NSString *info = userInfo[@"Notification"];
// 如果找到需要取消的通知漂问,則取消
if (info != nil) {
[[UIApplication sharedApplication] cancelLocalNotification:notification];
//圖標(biāo)的數(shù)字清零
([UIApplication sharedApplication].applicationIconBadgeNumber >= 1) ?([UIApplication sharedApplication].applicationIconBadgeNumber -= 1):0 ;
break;
}
}
}
}