本地通知-闹钟

本地通知简介:

本地通知简单来说app本身给应用程序推送消息,不需要服务器支持。使用场景:闹钟,定时操作。

1.创建本地通知

//  创建本地通知对象

UILocalNotification *localNoti = [[UILocalNotification alloc] init];

2.设置本地通知属性

NSDateFormatter *date_formatter = [[NSDateFormatter alloc] init];

[date_formatter setDateFormat:@"yyyy-MM-dd"];

NSString *TimeStr = [date_formatter stringFromDate:[NSDate date]];

/** 目前是定时每天九点,后续版本迭代在封装 */

TimeStr = [NSString stringWithFormat:@"%@ 09:00:00",TimeStr];

[date_formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

NSDate *dateTime = [date_formatter dateFromString:TimeStr];

//1.设置推送类型


UIUserNotificationType type = UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert;

//2.设置setting

UIUserNotificationSettings *setting  = [UIUserNotificationSettings settingsForTypes:type categories:nil];

//3.主动授权

[[UIApplication sharedApplication] registerUserNotificationSettings:setting];

//时区

localNoti.timeZone = [NSTimeZone defaultTimeZone];

//时间

localNoti.fireDate = dateTime;

//重复间隔

localNoti.repeatInterval = kCFCalendarUnitDay;

//通知内容

localNoti.alertBody = @"今日活动任务有到期";

//通知声音

localNoti.soundName = UILocalNotificationDefaultSoundName;

//    //通知参数

//    localNoti.userInfo = [NSDictionary dictionaryWithObject:@"NotificationStr" forKey:@"Notification"];

//发送通知:

[[UIApplication sharedApplication] scheduleLocalNotification:localNoti];


3.取消通知

#pragma mark -- 取消通知

- (void)cancelLocalNotification

{

// 获取所有本地通知数组

NSArray *localNotifications = [UIApplication sharedApplication].scheduledLocalNotifications;

for (UILocalNotification *notification in localNotifications) {

NSDictionary *userInfo = notification.userInfo;

if (userInfo) {

// 根据设置通知参数时指定的key来获取通知参数

NSString *info = userInfo[@"Notification"];

// 如果找到需要取消的通知,则取消

if (info != nil) {

[[UIApplication sharedApplication] cancelLocalNotification:notification];

//图标的数字清零

([UIApplication sharedApplication].applicationIconBadgeNumber >= 1) ?([UIApplication sharedApplication].applicationIconBadgeNumber -= 1):0 ;

break;

}

}

}

}

你可能感兴趣的:(本地通知-闹钟)