1,首先判断系统
if ([[UIDevice currentDevice].systemVersion floatValue] >= 10) {
[self registerNotification:1];
}else if([[UIDevice currentDevice].systemVersion floatValue] >= 8){
[self registerLocalNotificationInOldWay:2];
}
2,注册本地通知
- (void)registerLocalNotificationInOldWay:(NSInteger)alertTime {
// ios8后,需要添加这个注册,才能得到授权
// if ([[UIApplication sharedApplication] respondsToSelector:@selector(registerUserNotificationSettings:)]) {
// UIUserNotificationType type = UIUserNotificationTypeAlert | UIUserNotificationTypeBadge | UIUserNotificationTypeSound;
// UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:type
// categories:nil];
// [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
// // 通知重复提示的单位,可以是天、周、月
// }
UILocalNotification *notification = [[UILocalNotification alloc] init];
// 设置触发通知的时间
NSDate *date = [NSDate date];
NSTimeZone *zone = [NSTimeZone systemTimeZone];
NSInteger interval = [zone secondsFromGMTForDate: date];
NSDate *localeDate = [date dateByAddingTimeInterval: interval];
NSDate *fireDate = [localeDate dateByAddingTimeInterval:alertTime];
NSLog(@"fireDate=%@",fireDate);
notification.fireDate = fireDate;
// 时区
notification.timeZone = [NSTimeZone systemTimeZone];
// 设置重复的间隔
notification.repeatInterval = kCFCalendarUnitSecond;
// 通知内容
notification.alertBody = @"通知来了...";
notification.applicationIconBadgeNumber = 1;
// 通知被触发时播放的声音
notification.soundName = UILocalNotificationDefaultSoundName;
// 通知参数
NSDictionary *userDict = [NSDictionary dictionaryWithObject:@"开始学习iOS开发了" forKey:@"key"];
notification.userInfo = userDict;
// 执行通知注册
[[UIApplication sharedApplication] scheduleLocalNotification:notification];
}
//使用 UNNotification 本地通知
-(void)registerNotification:(NSInteger )alerTime{
// 使用 UNUserNotificationCenter 来管理通知
UNUserNotificationCenter* center = [UNUserNotificationCenter currentNotificationCenter];
//需创建一个包含待通知内容的 UNMutableNotificationContent 对象,注意不是 UNNotificationContent ,此对象为不可变对象。
UNMutableNotificationContent* content = [[UNMutableNotificationContent alloc] init];
content.title = [NSString localizedUserNotificationStringForKey:@"江南皮革厂倒闭啦!" arguments:nil];
content.body = [NSString localizedUserNotificationStringForKey:@"原价一百多两百多的商品,通通只要20元!"
arguments:nil];
content.sound = [UNNotificationSound defaultSound];
// 在 alertTime 后推送本地推送
UNTimeIntervalNotificationTrigger* trigger = [UNTimeIntervalNotificationTrigger
triggerWithTimeInterval:alerTime repeats:NO];
UNNotificationRequest* request = [UNNotificationRequest requestWithIdentifier:@"FiveSecond"
content:content trigger:trigger];
//添加推送成功后的处理!
[center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
}];
}
以上就是本地通知iOS 10和 iOS 8,9的区别;