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

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

一.手动配置

1.集成插件到项目中

rush:bash;"> 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

rush:plain;"> 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

rush:xml;"> figChanges="keyboard|keyboardHidden|orientation|screenSize" android:label="@string/app_name">

<Meta-data android:name="JPUSH_CHANNEL" android:value="${APP_CHANNEL}"/>
<Meta-data android:name="JPUSH_APPKEY" android:value="${JPUSH_APPKEY}"/>

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

修改 app 下的 build.gradle 配置:

rush:plain;"> 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 中加入如下库:

rush:plain;"> 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。

如图

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

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

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

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

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

1.引入依赖文件

rush:cpp;"> #import #ifdef NSFoundationVersionNumber_iOS_9_x_Max #import #endif

@interface AppDelegate()

@end

2.在didFinishLaunchingWithOptions方法添加

= 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的代码

rush:cpp;"> - (void)application:(UIApplication *)application

didRegisterForRemoteNotificationsWithDevicetoken:(NSData *)devicetoken {

[JPUSHService registerDevicetoken:devicetoken];

}

rush:cpp;"> - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {

// 取得 APNs 标准信息内容

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

}

这个方法是清除icon角标

rush:cpp;"> - (void)applicationWillEnterForeground:(UIApplication *)application { [application setApplicationIconBadgeNumber:0]; // [application cancelAlllocalnotifications]; }
rush:cpp;"> //iOS 7 Remote Notification
  • (void)application:(UIApplication )application didReceiveRemoteNotification: (NSDictionary )userInfo fetchCompletionHandler:(void (^) (UIBackgroundFetchResult))completionHandler {

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

}

rush:cpp;"> // 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三种类型可以选择设置

}

rush:cpp;"> // 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(); // 系统要求执行这个方法

}

rush:cpp;"> - (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {

//Optional

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

}

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

rush:cpp;"> //获取自定义消息 NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];

[defaultCenter addobserver:self selector:@selector(networkDidReceiveMess

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

rush:cpp;"> //#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的权限

往下滑动,配置:

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

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

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("<a href="https://www.jb51.cc/tag/opening/" target="_blank" class="keywords">opening</a> 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右上角角标显示的数字增加,如图:

加号为英文状态下的

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

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

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...