第一步发起通知.主要是date日期获取.可以在UIDatePicker或者calendar获取时间
mDatePicker.datePickerMode = .time
let date = mDatePicker.date
// 创建一个日期格式器
let dformatter = DateFormatter()
// 为日期格式器设置格式字符串
dformatter.dateFormat = "HH:mma"
// 使用日期格式器格式化日期、时间
let datestr = dformatter.string(from: date)
let message = "每天 \(datestr)"
NSLog(message)
// 设置日期
mTimeNotifyBtn.titleLabel?.text = message
let types = UIUserNotificationType.alert
let mySettings = UIUserNotificationSettings.init(types: types, categories: nil)
UIApplication.shared.registerUserNotificationSettings(mySettings)
let notification = UILocalNotification.init()
notification.fireDate = NSDate.init(timeInterval: 10.0, since: date) as Date
notification.alertBody = "您设置的练习时间到了"
notification.alertTitle="请打开EnglishLeanger";
notification.alertAction = "不要忘记学英语哦!";
notification.repeatInterval=NSCalendar.Unit.day
notification.applicationIconBadgeNumber=1;
notification.soundName=UILocalNotificationDefaultSoundName;
UIApplication.shared.scheduleLocalNotification(notification)
遇到的坑:
没有加入以下三行代码.提醒不出现
let types = UIUserNotificationType.alert
let mySettings = UIUserNotificationSettings.init(types: types, categories: nil)
UIApplication.shared.registerUserNotificationSettings(mySettings)
第二步,appdelegate里面设置
// 申请闹钟权限
if ([UIApplication instancesRespondToSelector:@selector(registerUserNotificationSettings:)]){
[application registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound categories:nil]];
}
else {
[application registerForRemoteNotificationTypes:UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge];
}
//获取本地通知
UILocalNotification * localNotify = [launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];
if(localNotify){
[self application:self didReceiveLocalNotification:localNotify];
}else {
}
[UIApplication sharedApplication].applicationIconBadgeNumber = 0;
ps :遇到的bug 没有动态获取权限,也不会显示通知,而且不报错
注意小红点的展示applicationIconBadgeNumber
需要点击后取消通知,不然会一直重复不断通知代码如下:
-(void) application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification{
[[UIApplication sharedApplication] cancelLocalNotification:notification];
}