安裝:
打開終端,進入項目文件夾,執(zhí)行以下命令:
//RN版本 < 0.40.0, 使用 v1.3.6版本
//npm 安裝
npm install jpush-react-native@1.3.6 --save
//yarn 安裝
yarn add jpush-react-native@1.3.6
yarn安裝教程參考:yarn安裝教程
//RN版本 > 0.40.0
//使用最新版本
//并且jpush-react-native > 1.4.4,需要同時安裝 jcore-react-native
npm install jpush-react-native --save
npm install jcore-react-native --save
安裝完成后,進行l(wèi)ink
//自動配置
react-native link
iOS配置
在 iOS 工程中如果找不到頭文件可能要在 TARGETS-> BUILD SETTINGS -> Search Paths -> Header Search Paths 添加如下如路徑
$(SRCROOT)/../node_modules/jpush-react-native/ios/RCTJPushModule/RCTJPushModule
打開 iOS 工程,在 rnpm link 之后,RCTJPushModule.xcodeproj 工程會自動添加到 Libraries 目錄里面
在 iOS 工程 target 的 Build Phases->Link Binary with Libraries 中加入如下庫
libz.tbd
CoreTelephony.framework
Security.framework
CFNetwork.framework
CoreFoundation.framework
SystemConfiguration.framework
Foundation.framework
UIKit.framework
UserNotifications.framework
libresolv.tbd
- 根據(jù)域名配置info.plist:
把需要的支持的域添加給NSExceptionDomains。其中jpush.cn作為Key,類型為字典類型。
每個域下面需要設(shè)置2個屬性:NSIncludesSubdomains、NSExceptionAllowsInsecureHTTPLoads。
兩個屬性均為Boolean類型,值分別為YES、YES。
- 在 AppDelegate.h 文件中 導入頭文件
#import <RCTJPushModule.h>
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif
- 在 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 的didFinishLaunchingWithOptions 方法里面添加如下代碼
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
if ([[UIDevice currentDevice].systemVersion floatValue] >= 10.0) {
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
entity.types = UNAuthorizationOptionAlert|UNAuthorizationOptionBadge|UNAuthorizationOptionSound;
[JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
#endif
} else if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
[JPUSHService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |
UIUserNotificationTypeSound |
UIUserNotificationTypeAlert)
categories:nil];
} else {
[JPUSHService registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |
UIRemoteNotificationTypeSound |
UIRemoteNotificationTypeAlert)
categories:nil];
}
[JPUSHService setupWithOption:launchOptions appKey:appKey
channel:channel apsForProduction:isProduction];
}
- 在AppDelegate.m 的didRegisterForRemoteNotificationsWithDeviceToken 方法中添加 [JPUSHService registerDeviceToken:deviceToken]; 如下所示
- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
[JPUSHService registerDeviceToken:deviceToken];
}
- 為了在收到推送點擊進入應(yīng)用能夠獲取該條推送內(nèi)容需要在 AppDelegate.m didReceiveRemoteNotification 方法里面添加 [[NSNotificationCenter defaultCenter] postNotificationName:kJPFDidReceiveRemoteNotification object:userInfo] 方法,注意:這里需要在兩個方法里面加一個是iOS7以前的一個是iOS7即以后的,如果AppDelegate.m 沒有這個兩個方法則直接復制這兩個方法,在 iOS10 的設(shè)備則可以使用JPush 提供的兩個方法;如下所示
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
// 取得 APNs 標準信息內(nèi)容
[[NSNotificationCenter defaultCenter] postNotificationName:kJPFDidReceiveRemoteNotification object:userInfo];
}
//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:kJPFOpenNotification object:userInfo];
}
completionHandler(); // 系統(tǒng)要求執(zhí)行這個方法
}
然后在 js 代碼里面通過如下回調(diào)獲取通知
var { NativeAppEventEmitter } = require('react-native');
var subscription = NativeAppEventEmitter.addListener(
'ReceiveNotification',
(notification) => console.log(notification)
);
...
// 千萬不要忘記忘記取消訂閱, 通常在componentWillUnmount函數(shù)中實現(xiàn)。
subscription.remove();
Android配置
Android執(zhí)行自動配置后仍然需要手動配置一下你項目模塊下的 build.gradle 文件,參見手動配置中的 build.gradle 配置(后續(xù)版本可能會改進這一點)
- 修改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)的配置復制到這個文件中,參考 demo 的 AndroidManifest:(增加了 <meta-data> 部分)
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
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 項目導進來了
Paste_Image.png
Add JPushPackage
RN 0.29.0以下版本
- 打開 app 下的 MainActivity,在 ReactInstanceManager 的 build 方法中加入 JPushPackage:
app/MainActivity.java
Paste_Image.png
RN 0.29.0 以上版本
- 打開 app 下的 MainApplication.java 文件,然后加入 JPushPackage,參考 demo:
app/MainApplication.java
private boolean SHUTDOWN_TOAST = false;
private boolean SHUTDOWN_LOG = false;
private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
@Override
protected boolean getUseDeveloperSupport() {
return BuildConfig.DEBUG;
}
@Override
protected List<ReactPackage> getPackages() {
return Arrays.<ReactPackage>asList(
new MainReactPackage(),
new JPushPackage(SHUTDOWN_TOAST, SHUTDOWN_LOG)
);
}
};
import JPushModule
import JPushModule from 'jpush-react-native';
...
// example
componentDidMount() {
JPushModule.addReceiveCustomMsgListener((message) => {
this.setState({pushMsg: message});
});
JPushModule.addReceiveNotificationListener((message) => {
console.log("receive notification: " + message);
})
}
componentWillUnmount() {
JPushModule.removeReceiveCustomMsgListener();
JPushModule.removeReceiveNotificationListener();
}