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 相关文章推荐
iframe的onload在Chrome/Opera中执行两次Bug的解决方法
Mar 17 Javascript
jQuery中验证表单提交方式及序列化表单内容的实现
Jan 06 Javascript
信息页文内画中画广告js实现代码(文中加载广告方式)
Jan 03 Javascript
JS实现Select的option上下移动的方法
Mar 01 Javascript
浅谈js的ajax的异步和同步请求的问题
Oct 07 Javascript
微信小程序 location API接口详解及实例代码
Oct 12 Javascript
微信小程序多列选择器range-key使用详解
Mar 30 Javascript
详解vue-cli下ESlint 配置说明
Sep 03 Javascript
详解vuex中action何时完成以及如何正确调用dispatch的思考
Jan 21 Javascript
详解小程序如何动态绑定点击的执行方法
Nov 26 Javascript
Vue事件处理原理及过程详解
Mar 11 Javascript
解决vuex刷新数据消失问题
Nov 12 Javascript
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
肝肠寸断了解下!盘点史上最伤心的十大动漫
2020/03/04 日漫
兼容PHP5的PHP目录管理函数库
2008/07/10 PHP
php更改目录及子目录下所有的文件后缀的代码
2010/09/24 PHP
示例详解Laravel重置密码代码重构
2016/08/10 PHP
PHP 中 DOMDocument保存xml时中文出现乱码问题的解决方案
2016/09/19 PHP
Laravel5.7 Eloquent ORM快速入门详解
2019/04/12 PHP
原生js做的手风琴效果的导航菜单
2013/11/08 Javascript
删除javascript中注释语句的正则表达式
2014/06/11 Javascript
jQuery.holdReady()方法用法实例
2014/12/27 Javascript
Jquery实现动态切换图片的方法
2015/05/18 Javascript
JS实现网页标题栏显示当前时间和日期的完整代码
2015/11/02 Javascript
js编写当天简单日历效果【实现代码】
2016/05/03 Javascript
使用AngularJS对表单提交内容进行验证的操作方法
2017/07/12 Javascript
详解在vue-cli中使用graphql即vue-apollo的用法
2018/09/08 Javascript
ES6 Map结构的应用实例分析
2019/06/26 Javascript
python进阶教程之词典、字典、dict
2014/08/29 Python
python通过imaplib模块读取gmail里邮件的方法
2015/05/08 Python
python读取与写入csv格式文件的示例代码
2017/12/16 Python
matplotlib绘制动画代码示例
2018/01/02 Python
Django中Forms的使用代码解析
2018/02/10 Python
10分钟用python搭建一个超好用的CMDB系统
2019/07/17 Python
利用python list完成最简单的DB连接池方法
2019/08/09 Python
python cv2读取rtsp实时码流按时生成连续视频文件方式
2019/12/25 Python
pytorch 实现张量tensor,图片,CPU,GPU,数组等的转换
2020/01/13 Python
python使用Geany编辑器配置方法
2020/02/21 Python
Python操作Jira库常用方法解析
2020/04/10 Python
python SOCKET编程基础入门
2021/02/27 Python
ALEX AND ANI:手镯,项链,耳环和更多
2017/04/20 全球购物
意大利宠物用品购物网站:Bauzaar
2018/09/15 全球购物
node中使用shell脚本的方法步骤
2021/03/23 Javascript
师范生自荐信范文
2013/10/06 职场文书
计算机网络专业个人的自我评价
2013/10/17 职场文书
《商鞅南门立木》教学反思
2014/02/16 职场文书
班班通校本培训方案
2014/03/12 职场文书
绿里奇迹观后感
2015/06/15 职场文书
Windows中Redis安装配置流程并实现远程访问功能
2021/06/07 Redis