作者:黑马理财投资 | 来源:互联网 | 2023-02-11 11:23
如何解决《iOS9中的UILocalNotification和iOS10中的UNMutableNotificationContent?》经验,为你挑选了1个好方法。
我需要向项目提供向后兼容性(iOS 9).我想出了这个:
if #available(iOS 10.0, *) {
let cOntent= UNMutableNotificationContent()
} else {
// Fallback on earlier versions
}
我应该在Fallback中写些什么?我是否需要创建本地通知实例?
1> Scar..:
以下是支持这两个版本的小例子:
Objective-c版本:
if #available(iOS 10.0, *) {
UNMutableNotificationContent *objNotificatiOnContent= [[UNMutableNotificationContent alloc] init];
objNotificationContent.body = @"Notifications";
objNotificationContent.badge = @([[UIApplication sharedApplication] applicationIconBadgeNumber] + 1);
UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:60 repeats:NO];
UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@"identifier" content:objNotificationContent trigger:trigger];
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
[center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
if (!error) {
}
else {
}
}];
}
else
{
UILocalNotification *localNotif = [[UILocalNotification alloc] init];
localNotif.fireDate = [[NSDate date] dateByAddingTimeIntervalInterval:60];
localNotif.alertBody = @"Notifications";
localNotif.repeatInterval = NSCalendarUnitMinute;
localNotif.applicatiOnIconBadgeNumber= 0;
[[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
}
Swift版本:
if #available(iOS 10.0, *) {
let cOntent= UNMutableNotificationContent()
content.categoryIdentifier = "awesomeNotification"
content.title = "Notification"
content.body = "Body"
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 60, repeats: false)
let request = UNNotificationRequest(identifier: "FiveSecond", content: content, trigger: trigger)
let center = UNUserNotificationCenter.current()
center.add(request) { (error) in
}
}
else
{
let notification = UILocalNotification()
notification.alertBody = "Notification"
notification.fireDate = NSDate(timeIntervalSinceNow:60)
notification.repeatInterval = NSCalendarUnit.Minute
UIApplication.sharedApplication().cancelAllLocalNotifications()
UIApplication.sharedApplication().scheduledLocalNotificatiOns= [notification]
}