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 相关文章推荐
浮动的div自适应居中显示的js代码
Dec 23 Javascript
通过onmouseover选项卡实现img图片的变化
Feb 12 Javascript
探寻Javascript执行效率问题
Nov 12 Javascript
JavaScript中String.match()方法的使用详解
Jun 06 Javascript
整理Javascript流程控制语句学习笔记
Nov 29 Javascript
js判断移动端是否安装某款app的多种方法
Dec 18 Javascript
jQuery实现下拉框多选 jquery-multiselect 的实例代码
Jul 14 Javascript
JavaScript使用forEach()与jQuery使用each遍历数组时return false 的区别
Aug 26 Javascript
简述vue中的config配置
Jan 23 Javascript
vue富文本编辑器组件vue-quill-edit使用教程
Sep 21 Javascript
Vue插件之滑动验证码用法详解
Apr 05 Javascript
vue使用svg文件补充-svg放大缩小操作(使用d3.js)
Sep 22 Javascript
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
PHP中file_exists函数不支持中文名的解决方法
2014/07/26 PHP
PHP实现链表的定义与反转功能示例
2018/06/09 PHP
PHP后台备份MySQL数据库的源码实例
2019/03/18 PHP
JavaScript 动态改变图片大小
2009/06/11 Javascript
jQueryUI如何自定义组件实现代码
2010/11/14 Javascript
jQuery简单实现banner图片切换
2014/01/02 Javascript
Node.js 服务器端应用开发框架 -- Hapi.js
2014/07/29 Javascript
js库Modernizr的介绍和使用
2015/05/07 Javascript
js简单网速测试方法完整实例
2015/12/15 Javascript
JS定时检测任务任务完成后执行下一步的解决办法
2016/12/22 Javascript
bootstrap按钮插件(Button)使用方法解析
2017/01/13 Javascript
Angular动态添加、删除输入框并计算值实例代码
2017/03/29 Javascript
微信小程序开发之从相册获取图片 使用相机拍照 本地图片上传
2017/04/18 Javascript
Vue入门之animate过渡动画效果
2018/04/08 Javascript
vue2.0 element-ui中el-select选择器无法显示选中的内容(解决方法)
2018/08/24 Javascript
bootstrap自定义样式之bootstrap实现侧边导航栏功能
2018/09/10 Javascript
Vue+Element实现表格编辑、删除、以及新增行的最优方法
2019/05/28 Javascript
JavaScript的查询机制LHS和RHS解析
2019/08/16 Javascript
vue+echarts+datav大屏数据展示及实现中国地图省市县下钻功能
2020/11/16 Javascript
Python爬虫之网页图片抓取的方法
2018/07/16 Python
pandas dataframe添加表格框线输出的方法
2019/02/08 Python
Python 异步协程函数原理及实例详解
2019/11/13 Python
django实现类似触发器的功能
2019/11/15 Python
python实现加密的方式总结
2020/01/19 Python
python代码实现将列表中重复元素之间的内容全部滤除
2020/05/22 Python
Python爬虫爬取糗事百科段子实例分享
2020/07/31 Python
使用anaconda安装pytorch的实现步骤
2020/09/03 Python
cookies应对python反爬虫知识点详解
2020/11/25 Python
爱护公共设施的标语
2014/06/24 职场文书
物理教育专业求职信
2014/06/25 职场文书
后勤管理员岗位职责
2014/08/27 职场文书
2014年督导工作总结
2014/11/19 职场文书
网吧温馨提示
2015/07/17 职场文书
基层党建工作简报
2015/07/21 职场文书
Redis分布式锁Redlock的实现
2021/08/07 Redis
vue项目如何打包之项目打包优化(让打包的js文件变小)
2022/04/30 Vue.js