iOS10 本地通知

iOS10之后,苹果对通知这块进行了大更新,把以前杂乱的API统一归类,放在了UserNotifications.framework框架中,比以前更加易用,还增加了撤回通知、更新已展示的通知,自定义自己的通知样式等强大的功能。本文仅介绍本地通知,远程推送需结合所使用的平台的相关文档(友盟、极光等)进行通知功能实现。

1、导入UserNotifications.framework

#import <UIKit/UILocalNotification.h>

2、在app启动的时候获取用户权限:

UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    [center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert) completionHandler:^(BOOL granted, NSError * _Nullable error) {

        if(granted) {
            NSLog(@"获取权限成功");
        }

    }];

3、创建本地通知

//定义通知的内容
UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc]init];
//通知标题
content.title = @"iOS10 本地通知";
//通知的副标题
content.subtitle = @"次级标题";
//通知的内容
content.body = @"本地通知的内容:10之后本地通知和远程推送合并为一个类了";
//发送通知后,app的角标数
content.badge = @1;
//自定义通知提示音 或是使用系统默认的: [UNNotificationSound defaultSound];
UNNotificationSound *sound = [UNNotificationSound soundNamed:@"in.caf"];
//指定提示音
content.sound = sound;
//指定通知触发的时间(TimeInterval:延时的时间,repeats:是否重复)
UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:3 repeats:NO];
//创建通知的请求对象
UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@"myLocal" content:content trigger:trigger];
//发送通知
[[UNUserNotificationCenter currentNotificationCenter] addNotificationRequest:request withCompletionHandler:nil];

UNTimeIntervalNotificationTrigger是新增的用来管理触发机制的,它还有以下几个类型:
UNPushNotificationTrigger(使用远程推送时使用),
UNCalendarNotificationTrigger(本地通知使用,用来在指定日期触发通知),
UNLocationNotificationTrigger(本地通知使用,用来在指定位置触发通知)。

另外,现在可以自定义通知样式,比如我想在通知中加入一张图片

//获取图片的路径
NSString *imageFilePath = [[NSBundle mainBundle] pathForResource:@"imageName" ofType:@"png"];
//创建一个Attachment对象
UNNotificationAttachment *imageAttachment = [UNNotificationAttachment attachmentWithIdentifier:@"imageAttachment" URL:[NSURL fileURLWithPath:imageFilePath] options:nil error:nil];
//指定给content
content.attachments = @[imageAttachment];

效果如下图
这里写图片描述

最后,我们可以在AppDelegate中的

-(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification

处理回调。以上就是本地通知的简单介绍。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值