React Native 集成jpush-react-native的示例代碼
jpush-React-native是極光推送官方維護(hù)的一個(gè)插件,github地址:https://github.com/jpush/jpush-react-native
一.手動(dòng)配置
1.集成插件到項(xiàng)目中
npm install jpush-react-native --save rnpm link jpush-react-native
Android
使用 android Studio import 你的 react Native 應(yīng)用(選擇你的 React Native 應(yīng)用所在目錄下的 android 文件夾即可)
修改 android 項(xiàng)目下的 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 相關(guān)的配置復(fù)制到這個(gè)文件中,參考 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" //應(yīng)用渠道號(hào)
]
}
}
...
dependencies {
compile fileTree(dir: "libs", include: ["*.jar"])
compile project(':jpush-react-native')
compile "com.facebook.react:react-native:+" // From node_modules
}
將此處的 yourApplicationId 替換為你的項(xiàng)目的包名;yourAppKey 替換成你在官網(wǎng)上申請(qǐng)的應(yīng)用的 AppKey。
現(xiàn)在重新 sync 一下項(xiàng)目,應(yīng)該能看到 jpush-react-native 作為一個(gè) android Library 項(xiàng)目導(dǎo)進(jìn)來(lái)了
重點(diǎn)來(lái)了,我在這個(gè)地方卡了一天,以上代碼配置完成后,但是不管怎么樣就是接收不到推送。
解決方案:找到項(xiàng)目/node_modules/jpush-react-native/android/src/main/AndroidManifest.xml,里面的 ${applicationId} 全部換成 你自己的項(xiàng)目包名
到此為止android的配置結(jié)束。
二.iOS配置
打開(kāi) ios 工程,在 rnpm link 之后,RCTJPushModule.xcodeproj 工程會(huì)自動(dòng)添加到 Libraries 目錄里面
在 iOS 工程 target 的 Build Phases->Link Binary with Libraries 中加入如下庫(kù):
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)
根據(jù)域名配置info.plist:
把需要的支持的域添加給NSExceptionDomains。其中jpush.cn作為Key,類型為字典類型。
每個(gè)域下面需要設(shè)置2個(gè)屬性:NSIncludesSubdomains、NSExceptionAllowsInsecureHTTPLoads。
兩個(gè)屬性均為Boolean類型,值分別為YES、YES。
如圖

在 AppDelegate.h 文件中 填寫如下代碼,這里的的 appkey、channel、和 isProduction 填寫自己的
static NSString *appKey = @”“; //填寫appkey
static NSString *channel = @”“; //填寫channel 一般為nil
static BOOL isProduction = false; //填寫isProdurion 平時(shí)測(cè)試時(shí)為false ,生產(chǎn)時(shí)填寫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 標(biāo)準(zhǔn)信息內(nèi)容
[[NSNotificationCenter defaultCenter] postNotificationName:kJPFDidReceiveRemoteNotification object:userInfo];
}
這個(gè)方法是清除icon角標(biāo)
- (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); // 需要執(zhí)行這個(gè)方法,選擇是否提醒用戶,有Badge、Sound、Alert三種類型可以選擇設(shè)置
}
// 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(); // 系統(tǒng)要求執(zhí)行這個(gè)方法
}
- (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
還需要添加新的方法,以監(jiān)聽(tīng)自定義消息的接受:
//#pragma mark 獲取自定義消息內(nèi)容
- (void)networkDidReceiveMessage:(NSNotification *)notification {
NSDictionary * userInfo = [notification userInfo];
NSString *content = [userInfo valueForKey:@"content"];
NSDictionary *extras = [userInfo valueForKey:@"extras"];
NSString *customizeField1 = [extras valueForKey:@"123456"]; //自定義參數(shù),key是自己定義的
NSLog(@"自定義message:%@",userInfo);
NSLog(@"推%@",content);
NSLog(@"推%@",extras);
NSLog(@"推%@",customizeField1);
}
配置代碼,在Xcode中打開(kāi)push的權(quán)限

往下滑動(dòng),配置:

到此為止,ios的配置結(jié)束。
然后在RN中配置調(diào)用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();
}
然后就可以去官方控制臺(tái),手動(dòng)推送通知了
想要icon右上角角標(biāo)顯示的數(shù)字增加,如圖:

加號(hào)為英文狀態(tài)下的
大家集成的時(shí)候多看官方文檔,將兩端的官方demo下載下來(lái),能發(fā)現(xiàn)很多有用的信息。
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
ahooks控制時(shí)機(jī)的hook實(shí)現(xiàn)方法
這篇文章主要為大家介紹了ahooks控制時(shí)機(jī)的hook實(shí)現(xiàn)方法示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-07-07
react-router-domV6嵌套路由實(shí)現(xiàn)詳解
這篇文章主要為大家介紹了react-router-domV6嵌套路由實(shí)現(xiàn)詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-01-01
關(guān)于React16.0的componentDidCatch方法解讀
這篇文章主要介紹了關(guān)于React16.0的componentDidCatch方法解讀,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-05-05
簡(jiǎn)單的React SSR服務(wù)器渲染實(shí)現(xiàn)
這篇文章主要介紹了簡(jiǎn)單的React SSR服務(wù)器渲染實(shí)現(xiàn),小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-12-12
react?component?function組件使用詳解
這篇文章主要為大家介紹了react?component?function組件的使用示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-11-11
React中關(guān)于render()的用法及說(shuō)明
這篇文章主要介紹了React中關(guān)于render()的用法及說(shuō)明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-02-02
React中使用Axios發(fā)起POST請(qǐng)求提交文件方式
這篇文章主要介紹了React中使用Axios發(fā)起POST請(qǐng)求提交文件方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-02-02
React通過(guò)hook實(shí)現(xiàn)封裝表格常用功能
這篇文章主要為大家詳細(xì)介紹了React通過(guò)hook封裝表格常用功能的使用,文中的示例代碼講解詳細(xì),具有一定的借鑒價(jià)值,有需要的小伙伴可以參考下2023-12-12

