参考Demo
实现本地通知只需要三步:
1. 注册本地通知
在didFinishLaunchingWithOptions
方法中,注册本地通知:
UIUserNotificationType types = UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert;
UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:types categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];
2. 接收通知
接收本地通知需要实现,这里需要注意的是,只有当APP在前台或者APP通过点击通知栏消息被唤醒(开启)时,才会执行这个方法:
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
// 在这里对通知消息做处理
}
3. 设置本地通知:
// 初始化本地通知对象
UILocalNotification*notification = [[UILocalNotification alloc] init];
if (notification) {
// 使用本地时区
notification.timeZone = [NSTimeZone defaultTimeZone];
// 5秒之后发出本地通知
notification.fireDate = [NSDate dateWithTimeIntervalSinceNow:5];
// 设置重复间隔
notification.repeatInterval = kCFCalendarUnitDay;
// 设置提醒的文字内容
notification.alertBody = @"Wake up, man";
notification.alertAction = NSLocalizedString(@"起床了", nil);
// 通知提示音 使用默认的
notification.soundName= UILocalNotificationDefaultSoundName;
// 设置icon角标
notification.applicationIconBadgeNumber++;
// 设定通知的userInfo,用来标识该通知
NSDictionary*info = [NSDictionary dictionaryWithObject:@"test" forKey:@"name"];
notification.userInfo = info;
// 设置本地通知
[[UIApplication sharedApplication] scheduleLocalNotification:notification];
}
角标
如果本地通知改变了icon角标,可以在接收通知的方法或者在applicationDidBecomeActive
里执行以下方法:
[UIApplication sharedApplication].applicationIconBadgeNumber = 0;
如果需要移除通知栏消息,则将上面的方法替换为以下方法:
[UIApplication sharedApplication].applicationIconBadgeNumber = 1;
[UIApplication sharedApplication].applicationIconBadgeNumber = 0;
是的没错,就多了一句给Badge赋值的语句,就可以清除通知栏消息了。