iOS 推送通知(上)

简介: iOS 推送通知(上)

总体内容


1.推送通知的介绍

2.本地通知

3.远程通知

4.极光推送的使用


一、推送通知的介绍



  • 1.1、推送通知的作用:让不在前台(后台或者关闭)的APP知道APP内部发生的事情,效果如下


image.png

image.png



提示:这里说的推送通知跟 NSNotification 有所区别


  • NSNotification 是抽象的,不可见的
  • 推送通知是可见的(能用肉眼看到)


  • 1.2、通知的分类
  • (1)、本地通知
  • 概念:由APP本身给应用程序推送消息,不需要服务器的支持
  • 常见场景:记账软件定时提醒记账/番茄工作法中提醒你时间等等
  • 注意:不是非常常用.


  • (2)、远程通知
  • 概念:由服务器推送消息给用户,需要服务器的支持
  • 常见场景:微信提醒新消息/淘宝提醒有新活动/视频软件提供您有最新电影
  • 注意:非常常用.但是如果仅仅是给用户提醒,客户端(你)做的事情就非常简单.


  • 1.3、推送通知的呈现样式
  • (1)、在屏幕顶部显示一块横幅


image.png

image.png


(2)、锁屏界面也可以显示


image.png

image.png



提示:收到通知还可以做如下操作


  • 收到通知时,同时播放音效.(比如支付宝或者微信收账语音提示)
  • 收到通知时,改变APP图标上的数字(app图标上的消息数量)


二、本地通知(不经常用),demo



  • 2.1、本地通知的介绍
  • 直接由应用程序(程序中写入对应代码)给用户发出通知
  • 本地通知需要用到一个重要的类: UILocalNotification
  • 本地通知的实现步骤:
  • (1)、创建本地通知
  • (2)、设置本地通知要发出的内容等信息
  • 发出时间
  • 发出内容
  • 播放的音效
  • (3)、调度本地通知
  • 2.2、实现本地通知
  • (1)、注册通知
  • iOS8 之后,如果想要发出通知(无论本地还是远程),必须先进行注册.(iOS8之前不需要)
  • 通常是在 AppDelegatedidFinishLaunchingWithOptions 中进行注册,代码如下


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
       if (@available(iOS 10.0, *)) {
            //iOS10
            UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
            center.delegate = self;
            [center requestAuthorizationWithOptions:(UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionBadge) completionHandler:^(BOOL granted, NSError * _Nullable error) {
            }];
        }else{
            /**
                // 不设置类型
                UIUserNotificationTypeNone    = 0,
                // 消息数量
                UIUserNotificationTypeBadge   = 1 << 0,
                // 声音
                UIUserNotificationTypeSound   = 1 << 1,
                // 弹出通知
                UIUserNotificationTypeAlert   = 1 << 2,
             */
             UIUserNotificationSettings *notificationSettings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert categories:nil];
             [application registerUserNotificationSettings:notificationSettings];
         }    
    return YES;
}


提示:UIUserNotificationSettings 在iOS10被废弃了,苹果推新的 UNUserNotificationCenter,使用UNUserNotificationCenter需要导入#import <UserNotifications/UserNotifications.h>,挂代理


  • (2)、创建并且发出通知
  • 使用 UIUserNotificationSettings(iOS 8.0~<iOS 10.0) 与 UNUserNotificationCenter((iOS 10.0及以后)


if (@available(iOS 10.0, *)) {
     // 消息标识
     NSString *identifier = @"request1";
     // 获取通知中心用来激活新建的通知
     UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
     // 通知的内容
     UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
     content.badge = [NSNumber numberWithInt:1];
     content.title = @"测试";
     content.body = @"干嘛呢";
     content.sound = [UNNotificationSound defaultSound];
     // 间隔多久推送一次
     //UNTimeIntervalNotificationTrigger   延时推送
     //UNCalendarNotificationTrigger       定时推送
     //UNLocationNotificationTrigger       位置变化推送
     // 当前时间之后的10s后推送一次(如果重复的话时间要大于等于60s)
     UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:10 repeats:NO];
     // 定时推送
     //NSDateComponents *dateCom = [[NSDateComponents alloc] init];
     // 每天下午3点10分推送
     // dateCom.hour = 15;
     // dateCom.minute = 10;
     // UNCalendarNotificationTrigger *trigger = [UNCalendarNotificationTrigger triggerWithDateMatchingComponents:dateCom repeats:YES];
     // 建立通知请求
     UNNotificationRequest *notificationRequest = [UNNotificationRequest requestWithIdentifier:identifier content:content trigger:trigger];
     // 将建立的通知请求添加到通知中心
     [center addNotificationRequest:notificationRequest withCompletionHandler:^(NSError * _Nullable error) {
         if (error) {
               NSLog(@"%@本地推送 :( 报错 %@",identifier,error);
         }else{
               NSLog(@"通知请求添加到通知中心 Success");
         } 
     }];
} else {
     // 1.创建本地通知
     UILocalNotification *localNotification = [[UILocalNotification alloc]init];
     // 2.设置通知显示的内容
     // 2.1、设置通知弹出的时间
     localNotification.fireDate = [NSDate dateWithTimeIntervalSinceNow:6];
     // 2.2、设置通知中心的标题
     localNotification.alertTitle = @"测试";
     // 2.3、设置提示信息
     localNotification.alertBody = @"干嘛呢";
     // 2.4、设置滑块显示的文字
     localNotification.alertAction = @"快点";
     // 2.5、设置通知的声音
     // 自定义声音
     // localNotification.soundName = @"buyao.wav";
     // 系统默认声音
     localNotification.soundName = UILocalNotificationDefaultSoundName;
     // 2.6、设置应用程序图标右上角的数字
     localNotification.applicationIconBadgeNumber = 1;
     // 3、调度本地通知(调度之后某个时刻会弹出通知)
     [[UIApplication sharedApplication]scheduleLocalNotification:localNotification];
}


提示:总体属性展示

// 设置通知弹出的时间

@property(nullable, nonatomic,copy) NSDate *fireDate;

// 时区,默认系统使用的时区

@property(nullable, nonatomic,copy) NSTimeZone *timeZone;

// 通知的重复间隔

@property(nonatomic) NSCalendarUnit repeatInterval;

// 重复日期

@property(nullable, nonatomic,copy) NSCalendar *repeatCalendar;

// 区域:当进入该区域时,就会发出一个通知

@property(nullable, nonatomic,copy) CLRegion *region NS_AVAILABLE_IOS(8_0);

// YES:进入某一个时区只会发出一次通知,NO:每次进入该区域都会发出通知

@property(nonatomic,assign) BOOL regionTriggersOnce NS_AVAILABLE_IOS(8_0);

// 提示信息

@property(nullable, nonatomic,copy) NSString *alertBody;

// 用于决定 alertAction 是否生效

@property(nonatomic) BOOL hasAction;

// 锁屏界面滑块下显示的文字

@property(nullable, nonatomic,copy) NSString *alertAction;

// 不需要设置

@property(nullable, nonatomic,copy) NSString *alertLaunchImage;

// 通知中心的标题

@property(nullable, nonatomic,copy) NSString *alertTitle NS_AVAILABLE_IOS(8_2);

// 设置通知发出时音效

@property(nullable, nonatomic,copy) NSString *soundName;

// 应用程序右上角的数字

@property(nonatomic) NSInteger applicationIconBadgeNumber;

// 额外信息

@property(nullable, nonatomic,copy) NSDictionary *userInfo;


  • (3)、移除通知


// 移除所有的通知
[[UIApplication sharedApplication] cancelAllLocalNotifications];
// 移除某个通知
// [[UIApplication sharedApplication] cancelLocalNotification:@"某个通知对象"];


提示:如果在iOS 10之后 UNUserNotificationCenter 可以如下移除通知, requestID 是标识符

[center removePendingNotificationRequestsWithIdentifiers:@[requestID]];
[center removeAllDeliveredNotifications];


  • 2.3、监听本地通知的点击


  • (1)、为什么要监听本地通知的点击?
  • 通知点击之后会发生什么事情?
    不管应用程序出于后台还是被杀死,点击通知都可以打开应用程序
  • 什么情况下需要监听用户点击了通知(不常用)
    比如:当用点击通知时,进入到某一个固定界面
  • (2)、监听本地通知的点击,应用程序分很多种状态
  • 在前台:如果在前台不需要进行页面跳转
  • 在后台:点击应用时进行页面的跳转
  • 被杀死:点击应用打开应用时,进行页面的跳转
  • 应用程序在前台或者后台时的代码如下


// 应用在前台时,也会收到该通知,这时不应该进行页面的跳转
-(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification{
     NSLog(@"本地通知的点击");
     /**
        UIApplicationStateActive, 前台
        UIApplicationStateInactive, 进入前台
        UIApplicationStateBackground 在后台
      */
     if (application.applicationState == UIApplicationStateActive)
     return; // 前台情况下 不做操作
     // 进行页面的跳转
}
  • 应用程序被杀死时的情况下不会走上面的代码,但是不管是在任何情况下都会走下面的代码,通过launchOptionskey来做出各种判断,代码如下


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
      if (@available(iOS 10.0, *)) {
         //iOS10
         UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
         center.delegate = self;
         [center requestAuthorizationWithOptions:(UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionBadge) completionHandler:^(BOOL granted, NSError * _Nullable error) 
         {
         }];
       }else{
         UIUserNotificationSettings *notificationSettings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert categories:nil];
         [application registerUserNotificationSettings:notificationSettings];
       }
      // 判断是否是通过点击通知打开了应用程序
      if (launchOptions[UIApplicationLaunchOptionsLocalNotificationKey]) {
          // 在app杀死的情况下,本地通知的所走的地方
      }
   return YES;
}


提示:对应 launchOptions 的其他常用 key 如下

  • 对应的是启动应用程序的的远程通知信息userInfo(NSDictionary)
    UIApplicationLaunchOptionsRemoteNotificationKey
  • 对应的是为启动应用程序的的本地通知对象(UILocalNotification)
    UIApplicationLaunchOptionsLocalNotificationKey
  • 对应的对象为启动URL(NSURL)
    UIApplicationLaunchOptionsURLKey
  • 从点击3D Touch iCon启动,对应的是点击的iCon的信息。
    UIApplicationLaunchOptionsShortcutItemKey
  • 有关蓝牙的操作
    UIApplicationLaunchOptionsBluetoothPeripheralsKey
    UIApplicationLaunchOptionsBluetoothCentralsKey
  • 对应启动的源应用程序的bundle ID (NSString)
    UIApplicationLaunchOptionsSourceApplicationKey


三、远程通知,demo



  • 3.1、什么是远程通知 ?


  • 概念:由服务器发送消息给用户弹出消息的通知(需要联网)
  • 远程推送服务,又称为 APNsApple Push Notification Services
  • APNs 通知:是指通过向 Apple APNs 服务器发送通知,到达 iOS 设备,由 iOS 系统提供展现的推送。用户可以通过 IOS 系统的 “设置” >> “通知” 进行设置,开启或者关闭某一个 App 的推送能力。


  • 3.2、为什么需要远程通知 ?


  • 例子:京东 搞活动,促销活动或者商品降价,想告知用户.但是该用户不经常打开京东APP.京东如何通知该用户有最新的活动呢?
  • 传统方式:只有用户打开了京东客户端,客户端向服务器请求是否有最新的活动,才能在APP中告知用户活动.
  • 局限性:只要用户关闭了app,就无法跟app的服务器沟通,无法从服务器上获得最新的数据内容
  • 远程通知的好处:不管用户打开还是关闭app,只要联网了,都能接收到服务器推送的远程通知


  • 3.3、远程通知的原理


  • (1)、原理图


image.png

  • (2)、为什么京东服务器不直接推消息给用户?
  • 在通常情况下服务器端是不能主动向客户端推消息的.
  • 如果想服务器端给客户端推消息,必须建立长连接
  • 京东客户端在处于后台时(app杀死的情况下)不能和服务器端建立长连接


  • (3)、为什么苹果服务器可以推消息给用户?
  • 所有的苹果设备,在联网状态下,都会与苹果的服务器建立长连接
  • 苹果建立长连接的作用: 时间校准、系统升级提示、查找我的iPhone、远程通知 等等
  • 常见疑惑:苹果在推送消息时,如何准确的推送给某一个用户,并且知道是哪一个APP ?
  • 在京东服务器把消息给苹果的APNs服务器时,必须告知苹果DeviceToken
  • 什么是 DeviceToken ?
  • DeviceToken是由用户手机的UDID和应用程序的BundleID共同生成的
  • 通过DeviceToken可以找到唯一手机中的唯一应用程序
  • 如何获得DeviceToken:客户端到苹果的APNs注册即可获得。


  • (4)、完整的流程图


image.png

  • 3.4、如何做远程通知 ?
  • 首先,BundleID对应的App ID必须是明确的(特殊功能)
  • 该APPID必须配置两个证书
  • 开发证书:用于调试远程推送
  • 发布证书:用于发布后给用户推送消息
  • 根据上面的App ID重新配置描述文件
  • 安装对应的证书,即可开始测试远程推送


  • 3.5、远程通知证书配置
  • (1)、我们先创建一个 CSR 文件(又叫做:证书签名请求文件)(下面会用到,它是用来绑定电脑的)
  • 找到 Launchpad 里面的 钥匙串访问


image.png

打开钥匙串访问->证书助理->从证书机构颁请求证书

image.png


出现如下界面,选择存储到磁盘,点击继续


image.png


选择存储到待会好找的地方(比如:桌面,自己建的文件夹等等),存储


image.png


(2)、在 Identifiers里面创建一个明确的App ID,如下


image.png

image.png

image.png

提示:Bundle ID 一定要填写明确的



目录
相关文章
|
11月前
|
iOS开发
iOS的推送通知,DeviceToken
iOS的推送通知,DeviceToken
157 2
|
消息中间件 存储 API
iOS小技能:队列管理推送通知,解决收款到账并发语音播报问题。
需求:收款到账语音提醒功能 NSE是比Voip更优雅的解决方案,完成迁移后,总体代码量也比Voip方案少了不少。
271 0
iOS小技能:队列管理推送通知,解决收款到账并发语音播报问题。
|
缓存 应用服务中间件 API
iOS 推送通知(下)
iOS 推送通知
241 0
iOS 推送通知(下)
|
网络安全 数据安全/隐私保护 iOS开发
|
iOS开发 数据安全/隐私保护
|
网络安全 数据安全/隐私保护 iOS开发
iOS推送通知的实现步骤
一.关于推送通知 来源:http://blog.csdn.net/enuola/article/details/8627283 推送通知,也被叫做远程通知,是在iOS 3.0以后被引入的功能。是当程序没有启动或不在前台运行时,告诉用户有新消息的一种途径,是从外部服务器发送到应用程序上的。
1230 0
|
网络安全 数据安全/隐私保护 iOS开发
如何配置iOS推送通知
<p>配置推送通知比较麻烦,需要iOS开发者帐号,然后配置一个Apple ID、配置概要文件和SSL证书。</p> <p><span id="more-150"></span></p> <p align="center"><a href="http://www.iosbook3.com/wp-content/uploads/2013/05/8.jpg"><img class="aligncen
1554 0
|
iOS开发 UED 自然语言处理
iOS 推送通知
引言: 推送通知是移动终端保持永远在线概念的一个核心方式,当人们离开桌面互联网以后想在第一时间收到与之相关的信息时.推送通知的出现就再好不过了. 但是,要注意不可滥用,繁多的非必要性推送消息会给用户造成非常烦躁的心理.
1645 0
|
1天前
|
搜索推荐 Android开发 iOS开发
探索安卓与iOS开发的差异性与互补性
【8月更文挑战第19天】在移动应用开发的广阔天地中,安卓与iOS两大平台各据一方,引领着行业的潮流。本文将深入探讨这两个平台在开发过程中的不同之处以及它们之间的互补关系,旨在为开发者提供一个全面的视角,帮助他们更好地把握市场动态,优化开发策略。通过分析各自的开发环境、编程语言、用户界面设计、性能考量及市场分布等方面,我们将揭示安卓与iOS开发的独特魅力和挑战,同时指出如何在这两者之间找到平衡点,实现跨平台的成功。