欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-09-08 20:19:17
jpush-react-native是极光推送官方维护的一个插件,github地址: 一.手动配置 1.集成插件到项目中 npm install jpu...

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

一.手动配置

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下载下来,能发现很多有用的信息。

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