iOS 9中的UILocalNotification和iOS 10中的UNMutableNotificationContent吗? [英] UILocalNotification in iOS 9 and UNMutableNotificationContent in iOS 10?

查看:161
本文介绍了iOS 9中的UILocalNotification和iOS 10中的UNMutableNotificationContent吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要为项目提供向后兼容性(iOS 9).我想到了这个:

I need to give backward compatibility (iOS 9) to a project. I came up with this:

if #available(iOS 10.0, *) {
        let content = UNMutableNotificationContent()
    } else {
        // Fallback on earlier versions
    }

我应该在Fallback中写些什么?我需要创建本地通知实例吗?

What should I write in Fallback? Do I need to create a local notification instance?

推荐答案

以下是支持两个版本的一个小示例:

Here is a small example on supporting both version:

Objective-c版本:

Objective-c version:

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中的UILocalNotification和iOS 10中的UNMutableNotificationContent吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆