react-native使用leanclound消息推送的方法


Posted in Javascript onAugust 06, 2018

iOS消息推送的基本流程

1.注册:为应用程序申请消息推送服务。此时你的设备会向APNs服务器发送注册请求。2. APNs服务器接受请求,并将deviceToken返给你设备上的应用程序 3.客户端应用程序将deviceToken发送给后台服务器程序,后台接收并储存。 4.后台服务器向APNs服务器发送推送消息 5.APNs服务器将消息发给deviceToken对应设备上的应用程序

使用leanclound进行消息推送

优势:文档清晰,价格便宜

接入Leanclound

1.首先需要创建一个react-native项目

react-native init projectName

2.在leancloud创建一个同名项目,并记录好appid和appkey

react-native使用leanclound消息推送的方法

react-native使用leanclound消息推送的方法

3.项目创建成功后,安装推送所需的模块(需要cd到工程目录)

1.使用yarn安装

yarn add leancloud-storage
yarn add leancloud-installation

2.使用npm安装

npm install leancloud-storage --save
npm install leancloud-installation --save

4.在项目目录下新建一个文件夹,名字为pushservice,在里面添加一个js文件PushService.js,处理消息推送的逻辑,

1.在index.js初始化leanclound

import AV from 'leancloud-storage'
...
/*
*添加注册的appid和appkey
*/
const appId = 'HT23EhDdzAfFlK9iMTDl10tE-gzGzoHsz'
const appKey = 'TyiCPb5KkEmj7XDYzwpGIFtA'
/*
*初始化
*/
AV.initialize(appId,appKey);
/*
*把Installation设为全局变量,在其他文件方便使用
*/
global.Installation = require('leancloud-installation')(AV);

...

2.iOS端配置

首先,在项目中引入RCTPushNotification,详情请参考: Linking Libraries - React Native docs

步骤一:将PushNotification项目拖到iOS主目录,PushNotification路径:当前项目/node_modules/react-native/Libraries/PushNotificationIOS目录下

步骤二:添加libRCTPushNotification静态库,添加方法:工程Targets-Build Phases-link binary with Libraries 点击添加,搜索libRCTPushNotification.a并添加

步骤三:开启推送功能,方法:工程Targets-Capabilities 找到Push Notification并打开

步骤四:在Appdelegate.m文件添加代码

#import <React/RCTPushNotificationManager.h>
...

//注册推送通知
-(void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings{
 [RCTPushNotificationManager didRegisterUserNotificationSettings:notificationSettings];
}
// Required for the register event.
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
 
 [RCTPushNotificationManager didRegisterForRemoteNotificationsWithDeviceToken:deviceToken];
}
// Required for the notification event. You must call the completion handler after handling the remote notification.
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
 NSLog(@"收到通知:%@",userInfo);
 [RCTPushNotificationManager didReceiveRemoteNotification:userInfo fetchCompletionHandler:completionHandler];
}
// Required for the registrationError event.
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
 NSLog(@"error == %@" , error);
 [RCTPushNotificationManager didFailToRegisterForRemoteNotificationsWithError:error];
}
// Required for the localNotification event.
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
 NSLog(@"接受通知:%@",notification);
 [RCTPushNotificationManager didReceiveLocalNotification:notification];
}

5. 获取deviceToken,并将deviceToken插入到_Installation

找到PushService文件,编写代码

//引用自带PushNotificationIOS
const PushNotificationIOS = require('react-native').PushNotificationIOS;
...
class PushService {
 //初始化推送
 init_pushService = () => {
  //添加监听事件
  PushNotificationIOS. addEventListener('register',this.register_push);
  //请求权限
  PushNotificationIOS.requestPermissions();
 }
 //获取权限成功的回调
 register_push = (deviceToken) => {
  //判断是否成功获取到devicetoken
  if (deviceToken) {
   this.saveDeviceToken(deviceToken);
  } 
 }
 //保存devicetoken到Installation表中
 saveDeviceToken = (deviceToken) => {
  global.Installation.getCurrent()
   .then(installation => {
   installation.set('deviceType', 'ios');
   installation.set('apnsTopic', '工程bundleid');
   installation.set('deviceToken', deviceToken);
   return installation.save();
  });
 }
 
}

修改App.js文件 在componentDidMount初始化推送

import PushService from './pushservice/PushService';
...
componentDidMount () {
 //初始化
 PushService.init_pushService();
}

运行项目,必须真机才能获取到deviceToken,模拟器获取不到,看看是否保存的deviceToken,如果保存成功,leandclound后台能发现_Installation表多了一条数据

react-native使用leanclound消息推送的方法

进行到这步了就已经完成了一半了,现在只需要配置推送证书即可接收推送消息,这里就不介绍配置证书流程了,详细步骤请参考 iOS推送证书设置,推送证书设置完成后,现在就去leanclound试试看能不能收到推送吧,退出APP,让APP处于后台状态,

react-native使用leanclound消息推送的方法

点击发送,看是不是收到了消息.

进行到这步骤说明推送已经完成了一大半了,APP当然还需要包括以下功能:

  • APP在前台、后台或者关闭状态下也能收到推送消息
  • 点击通知能够对消息进行操作,比如跳转到具体页面

APP处于前台状态时通知的显示

当APP在前台运行时的通知iOS是不会提醒的(iOS10后开始支持前台显示),因此需要实现的功能就是收到通知并在前端显示,这时候就要使用一个模块来支持该功能了,那就是react-native-message-bar

首先就是安装react-native-message-bar模块了

yarn add react-native-message-bar //yarn安装
或者
npm install react-native-message-bar --save //npm安装

安装成功之后,在App.js文件中引入并注册MessageBar

...
/*
*引入展示通知模块
 */
const MessageBarAlert = require('react-native-message-bar').MessageBar;
const MessageBarManager = require('react-native-message-bar').MessageBarManager;
...
componentDidMount () {
 //初始化
 PushService.init_pushService();
 MessageBarManager.registerMessageBar(this.alert);
}
...
render() {
 const {Nav} = this.state
 if (Nav) {
  return (
  //这里用到了导航,所以需要这样写,布局才不会乱 MessageBarAlert绑定一个alert
  <View style={{flex: 1,}}>
   <Nav />
   <MessageBarAlert ref={(c) => { this.alert = c }} />
  </View>
  )
 }
 return <View />
 }

然后再对PushService进行修改,新增对notification事件监听和推送消息的展示

import { AppState, NativeModules, Alert, DeviceEventEmitter } from 'react-native';
 ...
 //初始化推送
 init_pushService = () => {
  //添加监听事件
  PushNotificationIOS. addEventListener('register',this.register_push);
  PushNotificationIOS.addEventListener('notification', this._onNotification);
  //请求权限
  PushNotificationIOS.requestPermissions();
 }
 _onNotification = ( notification ) => {
  var state = AppState.currentState;
  // 判断当前状态是否是在前台
  if (state === 'active') {
   this._showAlert(notification._alert);
  }
 }
 ...
 _showAlert = ( message ) => {
  const MessageBarManager = require('react-native-message-bar').MessageBarManager;
  MessageBarManager.showAlert({
  title: '您有一条新的消息',
  message: message,
  alertType: 'success',
  stylesheetSuccess: {
   backgroundColor: '#7851B3', 
   titleColor: '#fff', 
   messageColor: '#fff'
  },
  viewTopInset : 20
 });

 }

 ...

最后重新运行APP并在leanclound发送一条消息,看是否在APP打开状态也能收到通知,到了这里推送就完成了

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Javascript 相关文章推荐
Span元素的width属性无效果原因及解决方案
Jan 15 Javascript
关于可运行代码无法正常执行的使用说明
May 13 Javascript
JQuery在光标位置插入内容的实现代码
Jun 18 Javascript
jQuery中使用了document和window哪些属性和方法小结
Sep 13 Javascript
jQuery实现的动态伸缩导航菜单实例
May 07 Javascript
javascript中Date()函数在各浏览器中的显示效果
Jun 18 Javascript
JQuery中模拟image的ajaxPrefilter与ajaxTransport处理
Jun 19 Javascript
javascript实现多栏闭合展开式广告位菜单效果实例
Aug 05 Javascript
情人节单身的我是如何在敲完代码之后收到12束玫瑰的(javascript)
Aug 21 Javascript
React Native预设占位placeholder的使用
Sep 28 Javascript
Vue单页面应用中实现Markdown渲染
Feb 14 Vue.js
vue实现简易音乐播放器
Aug 14 Vue.js
json数据传到前台并解析展示成列表的方法
Aug 06 #Javascript
使用js实现将后台传入的json数据放在前台显示
Aug 06 #Javascript
详解小程序原生使用ES7 async/await语法
Aug 06 #Javascript
JavaScript折半查找(二分查找)算法原理与实现方法示例
Aug 06 #Javascript
JavaScript插入排序算法原理与实现方法示例
Aug 06 #Javascript
微信小程序之多列表的显示和隐藏功能【附源码】
Aug 06 #Javascript
ES6 系列之 WeakMap的使用示例
Aug 06 #Javascript
You might like
兼容PHP5的PHP目录管理函数库
2008/07/10 PHP
php使用函数pathinfo()、parse_url()和basename()解析URL
2016/11/25 PHP
laravel实现一个上传图片的接口,并建立软链接,访问图片的方法
2019/10/12 PHP
Cookie 小记
2010/04/01 Javascript
JQuery的ajax获取数据后的处理总结(html,xml,json)
2010/07/14 Javascript
JQuery实现用户名无刷新验证的小例子
2013/03/22 Javascript
window.open()详解及浏览器兼容性问题示例探讨
2014/05/29 Javascript
JavaScript截取指定长度字符串点击可以展开全部代码
2015/12/04 Javascript
全面理解闭包机制
2016/07/11 Javascript
浅谈angularjs中响应回车事件
2017/04/24 Javascript
Mui使用jquery并且使用点击跳转新窗口的实例
2017/08/19 jQuery
node.js 利用流实现读写同步,边读边写的方法
2017/09/11 Javascript
nodeJS微信分享
2017/12/20 NodeJs
原生JS实现前端本地文件上传
2018/09/08 Javascript
微信小程序代码上传、审核发布小程序
2019/05/18 Javascript
Vue使用Proxy监听所有接口状态的方法实现
2019/06/07 Javascript
vue 实现移动端键盘搜索事件监听
2019/11/06 Javascript
vue页面更新patch的实现示例
2020/03/25 Javascript
解决Vue中的生命周期beforeDestory不触发的问题
2020/07/21 Javascript
利用Python批量生成任意尺寸的图片
2016/08/29 Python
详谈Python高阶函数与函数装饰器(推荐)
2017/09/30 Python
Python实现的字典值比较功能示例
2018/01/08 Python
解决Python获取字典dict中不存在的值时出错问题
2018/10/17 Python
python简易实现任意位数的水仙花实例
2018/11/13 Python
python创建学生管理系统
2019/11/22 Python
Python输出指定字符串的方法
2020/02/06 Python
浅谈Python中re.match()和re.search()的使用及区别
2020/04/14 Python
解决echarts中饼图标签重叠的问题
2020/05/16 Python
18-35岁旅游团的全球领导者:Contiki
2017/02/08 全球购物
复古风格的女装和装饰品:ModCloth
2017/12/29 全球购物
医学检验专业个人求职信范文
2013/12/04 职场文书
保护环境倡议书范文
2014/05/13 职场文书
2014年除四害工作总结
2014/12/06 职场文书
2015年机关作风和效能建设工作总结
2015/07/23 职场文书
MySQL的全局锁和表级锁的具体使用
2021/08/23 MySQL
MySQL8.0的WITH查询详情
2021/08/30 MySQL