這裏本地通知寫入是支持兩個版本的一個小例子:
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];
}
夫特版本:
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]
}
是的,我們需要編寫適用於iOS 9的回退邏輯,因爲在引入它們的操作系統版本之前不支持API。 –