React Native 集成jpush-react-native的示例代码


Posted in Javascript onAugust 16, 2017

jpush-React-native是极光推送官方维护的一个插件,github地址:https://github.com/jpush/jpush-react-native

一.手动配置

1.集成插件到项目中

npm install jpush-react-native --save
rnpm link jpush-react-native

Android

使用 android Studio import 你的 react Native 应用(选择你的 React Native 应用所在目录下的 android 文件夹即可)

修改 android 项目下的 settings.gradle 配置: settings.gradle

include ':app', ':jpush-react-native'
project(':jpush-react-native').projectDir = new File(rootProject.projectDir,'../node_modules/jpush-react-native/android')

修改 app 下的 AndroidManifest 配置,将 jpush 相关的配置复制到这个文件中,参考 demo 的 AndroidManifest:(增加了 部分)

your react native project/android/app/AndroidManifest.xml

<application
  android:name=".MainApplication"
  android:allowBackup="true"
  android:icon="@drawable/ic_launcher"
  android:label="@string/app_name"
  android:theme="@style/AppTheme">
  <activity
   android:name=".MainActivity"
   android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
   android:label="@string/app_name">
   <intent-filter>
    <action android:name="android.intent.action.MAIN" />
    <category android:name="android.intent.category.LAUNCHER" />
   </intent-filter>
  </activity>

  <activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />

  <!-- Required . Enable it you can get statistics data with channel -->
  <meta-data android:name="JPUSH_CHANNEL" android:value="${APP_CHANNEL}"/>
  <meta-data android:name="JPUSH_APPKEY" android:value="${JPUSH_APPKEY}"/>

 </application>

修改 app 下的 build.gradle 配置: your react native project/android/app/build.gradle

修改 app 下的 build.gradle 配置:

your react native project/android/app/build.gradle
android {
 defaultConfig {
  applicationId "yourApplicationId"
  ...
  manifestPlaceholders = [
    JPUSH_APPKEY: "yourAppKey", //在此替换你的APPKey
    APP_CHANNEL: "developer-default" //应用渠道号
  ]
 }
}
...
dependencies {
 compile fileTree(dir: "libs", include: ["*.jar"])
 compile project(':jpush-react-native')
 compile "com.facebook.react:react-native:+" // From node_modules
}

将此处的 yourApplicationId 替换为你的项目的包名;yourAppKey 替换成你在官网上申请的应用的 AppKey。

现在重新 sync 一下项目,应该能看到 jpush-react-native 作为一个 android Library 项目导进来了

重点来了,我在这个地方卡了一天,以上代码配置完成后,但是不管怎么样就是接收不到推送。

解决方案:找到项目/node_modules/jpush-react-native/android/src/main/AndroidManifest.xml,里面的 ${applicationId} 全部换成 你自己的项目包名

到此为止android的配置结束。

二.iOS配置

打开 ios 工程,在 rnpm link 之后,RCTJPushModule.xcodeproj 工程会自动添加到 Libraries 目录里面

在 iOS 工程 target 的 Build Phases->Link Binary with Libraries 中加入如下库:

CFNetwork.framework
CoreFoundation.framework
CoreTelephony.framework
SystemConfiguration.framework
CoreGraphics.framework
Foundation.framework
UIKit.framework
Security.framework
libz.tbd (Xcode7以下版本是libz.dylib)
UserNotifications.framework (Xcode8及以上)
libresolv.tbd (JPush 2.2.0及以上版本需要, Xcode7以下版本是libresolv.dylib)

根据域名配置info.plist:

把需要的支持的域添加?NSExceptionDomains。其中jpush.cn作为Key,类型为字典类型。

每个域下面需要设置2个属性:NSIncludesSubdomains、NSExceptionAllowsInsecureHTTPLoads。

两个属性均为Boolean类型,值分别为YES、YES。

如图

React Native 集成jpush-react-native的示例代码

在 AppDelegate.h 文件中 填写如下代码,这里的的 appkey、channel、和 isProduction 填写自己的

static NSString *appKey = @”“; //填写appkey

static NSString *channel = @”“; //填写channel 一般为nil

static BOOL isProduction = false; //填写isProdurion 平时测试时为false ,生产时填写true

在AppDelegate.m 里面添加如下代码

1.引入依赖文件

#import <RCTJPushModule.h>
 #ifdef NSFoundationVersionNumber_iOS_9_x_Max
 #import <UserNotifications/UserNotifications.h>
 #endif

 @interface AppDelegate()

 @end

2.在didFinishLaunchingWithOptions方法里添加

if ([[UIDevice currentDevice].systemVersion floatValue] >= 10.0) {

 JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];

 entity.types = UNAuthorizationOptionAlert|UNAuthorizationOptionBadge|UNAuthorizationOptionSound;

 [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];

 }else if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {

 //可以添加自定义categories
 [JPUSHService registerForRemoteNotificationTypes:(UNAuthorizationOptionBadge |
              UNAuthorizationOptionSound |
              UNAuthorizationOptionAlert)
           categories:nil];
 }else {

 //categories 必须为nil
 [JPUSHService registerForRemoteNotificationTypes:(UNAuthorizationOptionBadge |
              UNAuthorizationOptionSound |
              UNAuthorizationOptionAlert)
           categories:nil];
 }

 [JPUSHService setupWithOption:launchOptions appKey:appKey
      channel:nil apsForProduction:isProduction];

3.加入jupush的代码

- (void)application:(UIApplication *)application

didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {

 [JPUSHService registerDeviceToken:deviceToken];

}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {

 // 取得 APNs 标准信息内容

 [[NSNotificationCenter defaultCenter] postNotificationName:kJPFDidReceiveRemoteNotification object:userInfo];

}

这个方法是清除icon角标

- (void)applicationWillEnterForeground:(UIApplication *)application {
 [application setApplicationIconBadgeNumber:0];
// [application cancelAllLocalNotifications];
}
//iOS 7 Remote Notification

- (void)application:(UIApplication *)application didReceiveRemoteNotification: (NSDictionary *)userInfo fetchCompletionHandler:(void (^) (UIBackgroundFetchResult))completionHandler {

 [[NSNotificationCenter defaultCenter] postNotificationName:kJPFDidReceiveRemoteNotification object:userInfo];

}
// iOS 10 Support

- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {

 // Required

 NSDictionary * userInfo = notification.request.content.userInfo;

 if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {

 [JPUSHService handleRemoteNotification:userInfo];

 [[NSNotificationCenter defaultCenter] postNotificationName:kJPFDidReceiveRemoteNotification object:userInfo];

 }

 completionHandler(UNNotificationPresentationOptionAlert); // 需要执行这个方法,选择是否提醒用户,有Badge、Sound、Alert三种类型可以选择设置

}
// iOS 10 Support

- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {

 // Required

 NSDictionary * userInfo = response.notification.request.content.userInfo;

 if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {

 [JPUSHService handleRemoteNotification:userInfo];

 [[NSNotificationCenter defaultCenter] postNotificationName:kJPFDidReceiveRemoteNotification object:userInfo];

 }

 completionHandler(); // 系统要求执行这个方法

}
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {

 //Optional

 NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);

}

如果想要获取到自定义消息的话,需要在didFinishLaunchingWithOptions方法中添加一下代码:

//获取自定义消息
 NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];

 [defaultCenter addObserver:self selector:@selector(networkDidReceiveMess

还需要添加新的方法,以监听自定义消息的接受:

//#pragma mark 获取自定义消息内容

- (void)networkDidReceiveMessage:(NSNotification *)notification {

 NSDictionary * userInfo = [notification userInfo];

 NSString *content = [userInfo valueForKey:@"content"];

 NSDictionary *extras = [userInfo valueForKey:@"extras"];

 NSString *customizeField1 = [extras valueForKey:@"123456"]; //自定义参数,key是自己定义的

 NSLog(@"自定义message:%@",userInfo);

 NSLog(@"推%@",content);

 NSLog(@"推%@",extras);

 NSLog(@"推%@",customizeField1);

}

 配置代码,在Xcode中打开push的权限

React Native 集成jpush-react-native的示例代码

往下滑动,配置:

React Native 集成jpush-react-native的示例代码

到此为止,ios的配置结束。

然后在RN中配置调用jpush的代码:

import JPushModule from 'jpush-react-native';
 
constructor(props) {
  super(props);
  if(Platform.OS === 'android') JPushModule.initPush();
 }
componentDidMount(){
  if (Platform.OS === 'android') {
   BackAndroid.addEventListener('hardwareBackPress', this._onBackAndroid);

   //-----------jpush android start
   // JPushModule.getInfo((map) => {
   //  console.log(map);
   // });
   // JPushModule.addReceiveCustomMsgListener((message) => {
   // });
   JPushModule.addReceiveNotificationListener((message) => {
    console.log("receive notification: ");
    console.log(message);
   });
   JPushModule.addReceiveOpenNotificationListener((map) => {

    console.log("Opening notification!");
    console.log(map);
   });
   //-----------jpush android end
  }


  //-----------jpush ios start
  if (Platform.OS === 'ios') {
   this.subscription = NativeAppEventEmitter.addListener(
    'ReceiveNotification',
    (notification) => {
     console.log('-------------------收到推送----------------');
     console.log(notification)
    }
   );
  }
  //-----------jpush ios end
 }

 componentWillUnmount(){
  if (Platform.OS === 'android') {
   BackAndroid.removeEventListener('hardwareBackPress', this._onBackAndroid);
  }
  JPushModule.removeReceiveCustomMsgListener();
  JPushModule.removeReceiveNotificationListener();
  this.subscription && this.subscription.remove();
 }

 然后就可以去官方控制台,手动推送通知了

想要icon右上角角标显示的数字增加,如图:

React Native 集成jpush-react-native的示例代码

加号为英文状态下的

大家集成的时候多看官方文档,将两端的官方demo下载下来,能发现很多有用的信息。

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

Javascript 相关文章推荐
textContent在Firefox下与innerText等效的属性
May 12 Javascript
js 日期转换成中文格式的函数
Jul 07 Javascript
javascript中substr,substring,slice.splice的区别说明
Nov 25 Javascript
javascript 弹出层组件(升级版)
May 12 Javascript
js新闻滚动 js如何实现新闻滚动效果
Jan 07 Javascript
探讨在JQuery和Js中,如何让ajax执行完后再继续往下执行
Jul 09 Javascript
二叉树先序遍历的非递归算法具体实现
Jan 09 Javascript
jquery通过select列表选择框对表格数据进行过滤示例
May 07 Javascript
Javascript 事件冒泡机制详细介绍
Oct 10 Javascript
javascript 利用arguments实现可变长参数
Nov 21 Javascript
利用n 升级工具升级Node.js版本及在mac环境下的坑
Feb 15 Javascript
使用jquery DataTable和ajax向页面显示数据列表的方法
Aug 09 jQuery
jQuery实现全选、反选和不选功能
Aug 16 #jQuery
微信小程序注册60s倒计时功能 使用JS实现注册60s倒计时功能
Aug 16 #Javascript
微信小程序删除处理详解
Aug 16 #Javascript
微信小程序实现倒计时60s获取验证码
Apr 17 #Javascript
微信小程序实现根据字母选择城市功能
Aug 16 #Javascript
前端跨域的几种解决方式总结(推荐)
Aug 16 #Javascript
es6+angular1.X+webpack 实现按路由功能打包项目的示例
Aug 16 #Javascript
You might like
php版微信自动获取收货地址api用法示例
2016/09/22 PHP
PHP使用Redis替代文件存储Session的方法
2017/02/15 PHP
PHP封装的分页类与简单用法示例
2019/02/25 PHP
Yii框架的redis命令使用方法简单示例
2019/10/15 PHP
Javascript 学习笔记 错误处理
2009/07/30 Javascript
浏览器打开层自动缓慢展开收缩实例代码
2013/07/04 Javascript
jquery实现公告翻滚效果
2015/02/27 Javascript
JavaScript让网页出现渐隐渐显背景颜色的方法
2015/04/21 Javascript
基于canvas实现的钟摆效果完整实例
2016/01/26 Javascript
基于jQuery Ajax实现上传文件
2016/03/24 Javascript
BootStrap实现树形目录组件代码详解
2016/06/21 Javascript
jQuery属性选择器用法示例
2016/09/09 Javascript
BootStrap树状图显示功能
2016/11/24 Javascript
JS基于ES6新特性async await进行异步处理操作示例
2019/02/02 Javascript
细述Javascript的加法运算符的具体使用
2019/10/18 Javascript
Vue-Cli项目优化操作的实现
2019/10/27 Javascript
vue项目中使用eslint+prettier规范与检查代码的方法
2020/01/16 Javascript
jQuery实现移动端扭蛋机抽奖
2020/11/08 jQuery
小程序自定义圆形进度条
2020/11/17 Javascript
Python实现获取操作系统版本信息方法
2015/04/08 Python
解决Python出现_warn_unsafe_extraction问题的方法
2016/03/24 Python
JSON Web Tokens的实现原理
2017/04/02 Python
python获取命令行输入参数列表的实例代码
2018/06/23 Python
python用BeautifulSoup库简单爬虫实例分析
2018/07/30 Python
Python实现的旋转数组功能算法示例
2019/02/23 Python
libreoffice python 操作word及excel文档的方法
2019/07/04 Python
美国高档百货Nordstrom的折扣店:Nordstrom Rack
2017/11/13 全球购物
美国奢侈品在线团购网站:Gilt City
2017/11/16 全球购物
Feelunique德国官方网站:欧洲最大的在线美容零售商
2019/07/20 全球购物
农行实习自我鉴定
2013/09/22 职场文书
大学生毕业自我鉴定
2013/11/06 职场文书
公司业务主管岗位职责
2013/12/07 职场文书
2014学习十八届四中全会精神思想汇报范文
2014/10/23 职场文书
医院合作意向书范本
2015/05/08 职场文书
欠条范文
2015/07/03 职场文书
公司周年庆寄语
2019/06/21 职场文书