主要步骤
1.开启权限
if ([[UIApplication sharedApplication] currentUserNotificationSettings].types != UIUserNotificationTypeNone) {
[self addLocalNotification];
}else{
[[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound categories:nil]];
}
2. 添加本地推送私有方法
#pragma mark - 添加本地通知
- (void)addLocalNotification{
UILocalNotification *notification = [[UILocalNotification alloc]init];
notification.timeZone = [NSTimeZone defaultTimeZone];
notification.fireDate = [NSDate dateWithTimeIntervalSinceNow:5];
notification.repeatInterval = 2;
notification.repeatInterval = NSCalendarUnitDay;
notification.alertBody = @"hello, everyone";
notification.alertAction = @"I'm Kevin";
notification.applicationIconBadgeNumber++;
notification.soundName = UILocalNotificationDefaultSoundName;
notification.userInfo = @{@"id":@1, @"user":@"Kevin"};
[[UIApplication sharedApplication] scheduleLocalNotification:notification];
}
3.处理通知
#pragma mark - 进入前台后设置消息信息
- (void)applicationWillEnterForeground:(UIApplication *)application {
[[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
}
#pragma mark - 调用过用户注册通知方法之后执行
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings{
if (notificationSettings.types != UIUserNotificationTypeNone) {
[self addLocalNotification];
}
}
4.移除通知
#pragma mark - 移除本地通知
- (void)removeNotification{
[[UIApplication sharedApplication] cancelAllLocalNotifications];
}