iOS10更新_本地通知新框架UserNotifications

本文介绍在iOS10之前和之后本地通知的实现方式变化。早期使用`UILocalNotification`进行通知设置,包括警报标题、触发时间等。iOS10之后采用`UNNotificationContent`和`UNNotificationTrigger`进行更灵活的通知管理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在iOS之前,我们这样使用本地通知

- (void)viewDidLoad {
    [super viewDidLoad];

    UIUserNotificationSettings *setting = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge | UIUserNotificationTypeAlert | UIUserNotificationTypeSound categories:nil];

    [[UIApplication sharedApplication]registerUserNotificationSettings:setting];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    //创建本地通知
    UILocalNotification *notification = [UILocalNotification new];

    //设置本地 相关属性
    notification.alertTitle = @"测试";
    notification.timeZone = [NSTimeZone defaultTimeZone];
    notification.fireDate = [NSDate dateWithTimeIntervalSinceNow:3];
    notification.soundName = UILocalNotificationDefaultSoundName;
    notification.alertBody = @"推送内容";
    notification.applicationIconBadgeNumber = 1;

    //调度本地通知
    [[UIApplication sharedApplication] scheduleLocalNotification:notification];
}

在iOS10开始,这些方法都给出了警告,出现了新的方法替代了这些方法

这里写图片描述

使用通知时候我们需要加入新的框架

#import <UserNotifications/UserNotifications.h>
- (void)viewDidLoad {
    [super viewDidLoad];

    //UNNotificationSettings,新的替代类,但是目前里面的属性都是readOnly
    UIUserNotificationSettings *setting = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge | UIUserNotificationTypeAlert | UIUserNotificationTypeSound categories:nil];
    [[UIApplication sharedApplication]registerUserNotificationSettings:setting];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    //设置本地通知相关属性
    //用UNNotificationContent的子类UNMutableNotificationContent实现
    UNMutableNotificationContent *content = [UNMutableNotificationContent new];
    //设置应用程序的数字图标
    content.badge = @10;
    //设置声音
    content.sound = [UNNotificationSound defaultSound];
    //设置文字
    content.title = @"测试";
    content.subtitle = @"小标题";
    content.body = @"推送内容";


    //设置触发时间和重复,用UNNotificationTrigger的子类UNTimeIntervalNotificationTrigger实现
    //NSTimeInterval发送通知时间
    //repeats是否重复
    UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:3 repeats:NO];

    UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@"identifer" content:content trigger:trigger];

    //通过用户通知中心来添加一个本地通知的请求
    [[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
        //回调
    }];
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值