您好,登錄后才能下訂單哦!
小編給大家分享一下React Native如何集成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。
如圖
在 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的權限
往下滑動,配置:
到此為止,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”這篇文章的所有內容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內容對大家有所幫助,如果還想學習更多知識,歡迎關注億速云行業資訊頻道!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。