React Native 集成jpush-react-native的示例代碼
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 應(yīng)用(選擇你的 React Native 應(yīng)用所在目錄下的 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 相關(guān)的配置復(fù)制到這個文件中,參考 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)用渠道號
]
}
}
...
dependencies {
compile fileTree(dir: "libs", include: ["*.jar"])
compile project(':jpush-react-native')
compile "com.facebook.react:react-native:+" // From node_modules
}
將此處的 yourApplicationId 替換為你的項目的包名;yourAppKey 替換成你在官網(wǎng)上申請的應(yīng)用的 AppKey。
現(xiàn)在重新 sync 一下項目,應(yīng)該能看到 jpush-react-native 作為一個 android Library 項目導(dǎo)進(jìn)來了
重點來了,我在這個地方卡了一天,以上代碼配置完成后,但是不管怎么樣就是接收不到推送。
解決方案:找到項目/node_modules/jpush-react-native/android/src/main/AndroidManifest.xml,里面的 ${applicationId} 全部換成 你自己的項目包名
到此為止android的配置結(jié)束。
二.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)
根據(jù)域名配置info.plist:
把需要的支持的域添加給NSExceptionDomains。其中jpush.cn作為Key,類型為字典類型。
每個域下面需要設(shè)置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 ,生產(chǎn)時填寫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];
}
這個方法是清除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í)行這個方法,選擇是否提醒用戶,有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í)行這個方法
}
- (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)聽自定義消息的接受:
//#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中打開push的權(quán)限

往下滑動,配置:

到此為止,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();
}
然后就可以去官方控制臺,手動推送通知了
想要icon右上角角標(biāo)顯示的數(shù)字增加,如圖:

加號為英文狀態(tài)下的
大家集成的時候多看官方文檔,將兩端的官方demo下載下來,能發(fā)現(xiàn)很多有用的信息。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
React中useCallback useMemo到底該怎么用
在React函數(shù)組件中,當(dāng)組件中的props發(fā)生變化時,默認(rèn)情況下整個組件都會重新渲染。換句話說,如果組件中的任何值更新,整個組件將重新渲染,包括沒有更改values/props的函數(shù)/組件。在react中,我們可以通過memo,useMemo以及useCallback來防止子組件的rerender2023-02-02
React前端渲染優(yōu)化--父組件導(dǎo)致子組件重復(fù)渲染的問題
本篇文章是針對父組件導(dǎo)致子組件重復(fù)渲染的優(yōu)化方法,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-08-08
react中value與defaultValue的區(qū)別及說明
這篇文章主要介紹了react中value與defaultValue的區(qū)別及說明,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-05-05

