For react native App the push notification service is used with the help of TencentCloud in many countries like China. This document contains Tencent Cloud integration steps and code.
Below steps are to integrate 3 manufacturers Google Huawei and iOS in Tencent Cloud for a react native project.
When login to Tenentcloud make an application that will be added in code.
Goto Application management in Tenent Cloud im console.
Press Create new app button and make app with folder name
of app like myapp.After creating app press Application details and see app
information
Add the application in console add user in console this new application that userSig will be used for login
Account management for myapp press
Create new User and make it.
Access Settings
in console for myapp Access settings
Add huawei configuration and get certificate ID that
will be used with huawie device token (see huawei account config
information below).Press Quick Configuration on right side new window appear
that will show steps.Download timpush-configs.json file and place it in
android/app/src/assets/htmal folder.
On press Next step add project configuration.
- Add Package Name , App ID , AppSecret from the huawei
- Add agconnect-services.json huawei to android/app folder.
then press Next step again
Add implemention files to app level build.gradle file
Press Next step
and verify that huawai is added to tencent cloud.
Repeat these step for FCM
React Native Firebase https://rnfirebase.io/
Cloud Messaging https://rnfirebase.io/messaging/usage
For Fcm make an app android app com.myapp firebase and config it in tencent like this
- Add Application package name and Certificate address from firebase console
after successful adding it push it Certificate ID with fcmToken to tencentcloud.
test fcm from https://testfcm.com/
iOS Setup
See the pages given below
https://cloud.tencent.com/document/product/269/75429?from_cn_redirect=1
https://www.tencentcloud.com/document/product/1047/39157
https://www.tencentcloud.com/document/product/1024/35770?!editLang=zh
Make .p8 or .p12 from apple console for production and
development by enabling Push Service for myapp and
download it from there and add it in tencent manufacturer.From apple add KeyId
Add TeamId also from apple acount
Add app bundle id in the last.
Now testing the push
Get Certificate Id . Push apple token and bussness id (tencent user-id).
To login from react native add user id that was created
abovePress Generate signature and get the token. use this token
in react native to login tencentcloud to use servicesPaste the userSig
Verify the user before use.
Push Test (Access Test)
In tencent cloud im press Access Test
Add user-id like 123456 and press get status see if the device
is offline.Enter user-id press get token binding status button if the user
device and token is available.Press send a push test button by selecting certificate id that
are created above.
Huawei setup
Read below pages for help
https://ibjects.medium.com/how-to-submit-your-react-native-app-to-huawei-appgallery-6861c2696bda
https://developer.huawei.com/consumer/cn/service/josp/agc/index.html#/myProject
Open Huawei and in Project add the application myapp.
Open My project in Huawei console
Click My application
Press new button and add myapp as android app
Download agconnect-services.json and add it to android/app folder
Add these line to android level build.gragle file
Add the above lines to app level build.gradle file.
In My project select app in project settings
myapp will be selected
Select conventional
Get developer id if needed
In project get project id if required
Set data center and get client id it will be used in tencent
Client secret it will be used also in tencent
Get api key if needed
Download agconnect-services.json it will be place in project
android/app/ folder if required again.
after there step perform below step
Scroll down add sha26 key of your working machine
Use Client Id and
Client Secret for integration
in push service open panel
press Add push notification
Fill the Message content (form)
Press submit to see notification on device
React native Code
Now from add @hmscore/react-native-hms-push @react-native-firebase/messaging @react-native-community/push-notification-ios react-native-tim-js and @hmscore/react-native-hms-push packages in project with there configurations to use Tencentcloud in react native.
import TencentImSDKPlugin like below
import { TencentImSDKPlugin} from 'react-native-tim-js';
add sdkAppID from tencentcloud const sdkAppID = 123....;
then make listener like below
const sdkListener = {
onConnectFailed: (code: any, error: any) => {
console.log('sdkListener code ', code);
if (error) {
console.log('sdkListener error ', error);
}
},
onConnectSuccess: () => {
console.log('............ onConnectSuccess ............ ');
},
onConnecting: () => { },
onKickedOffline: () => { },
onSelfInfoUpdated: (info: V2TimUserFullInfo) => {
console.log(' info ======= isss..... ', info);
},
onUserSigExpired: () => { },
onUserStatusChanged: () => { },
};
Now initialise the listener from Tencent server like below code
useEffect(() => {
initSDK();
return () => void (isMountedRef.current = false);
}, []);
// start of TimPushPlugin work
const initSDK = async () => {
const initSDKRes = await
TencentImSDKPlugin.v2TIMManager.initSDK(
sdkAppID,
LogLevelEnum.V2TIM_LOG_DEBUG,
sdkListener
);
// console.log('--------- initSDKRes ------ ', initSDKRes);
if (initSDKRes.code === 0) {
userLogin();
}
}
when initSDKRes.code === 0 means sdk initialise is successful and now need to login business id and userSig from tencentcloud created just like above in this document.
const userLogin = async () => {
const businessID = 123456;
const user_sig = 'eJwtzEELwiAYxvHv4jmGu.....'
const res = await
TencentImSDKPlugin.v2TIMManager.login(businessID.toString(),
user_sig);
// console.log('userLogin login ====>> res', res);
if (res.code === 0) {
offlinePushConfig();
}
}
if the res.code === 0 it mean user is login to tencentcloud im successful
now its time to send deviceToken from manufacturer service to tencentcloud on which device will recieve push notification
For FCM
import messaging from '@react-native-firebase/messaging';
const fcmtoken = await messaging().getToken();
const setOfflinePushConfig = await TencentImSDKPlugin.v2TIMManager
.getOfflinePushManager()
.setOfflinePushConfig(7576, fcmtoken, false);
if (setOfflinePushConfig.code === 0) {
// console.log('---- ', setOfflinePushConfig);
}
for FCM use certificate id and fcmToken.
For iOS
AppDelegate.h
#import <RCTAppDelegate.h>
#import <UIKit/UIKit.h>
#import <UserNotifications/UNUserNotificationCenter.h>
@interface AppDelegate : RCTAppDelegate <UNUserNotificationCenterDelegate>
@property (nonatomic, strong) NSString *apnsCertificateID;
@end
AppDelegate.mm
#import "AppDelegate.h"
#import "FirebaseCore.h"
#import "Firebase.h"
#import <ImSDK_Plus/ImSDK_Plus.h>
#import <React/RCTBundleURLProvider.h>
#import <UserNotifications/UserNotifications.h>
#import <RNCPushNotificationIOS.h>
NSString *apnsCertificateID;
@implementation AppDelegate
- (NSURL *)sourceURLForBridge:(RCTBridge *)bridge
{
return [self getBundleURL];
}
- (NSURL *)getBundleURL
{
#if DEBUG
return [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index"];
#else
return [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"];
#endif
}
#pragma mark - TIMPush - (int)offlinePushCertificateID { return kAPNSBusiId; }
// Required for the register event.
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
[RNCPushNotificationIOS didRegisterForRemoteNotificationsWithDeviceToken:deviceToken ];
if ( deviceToken ) {
V2TIMAPNSConfig *confg = [ [ V2TIMAPNSConfig alloc ] init ] ;
// Enterprise certificate ID
// The user registers a developer certificate with Apple,
// downloads and generates the certificate ( p12 file )in the
// developer account , and transfers the generated p12 file to the
// Tencent Certificate Management Console.
// The console will automatically generate a certificate
// ID, and pass the certificate ID into the busiId parameter.
confg.businessID = 15899 ;
confg.token = deviceToken ;
confg.isTPNSToken = NO ;
[ [ V2TIMManager sharedInstance ] setAPNS:confg succ:^ {
NSLog ( @ "%s, succ" , __func__ ) ;
} fail:^ ( int code, NSString *msg ) {
NSLog ( @ "%s, fail, %d, %@" , __func__, code, msg ) ;
} ] ;
}
}
// Required for the notification event. You must call the completion handler after handling the remote notification.
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
[RNCPushNotificationIOS didReceiveRemoteNotification:userInfo fetchCompletionHandler:completionHandler];
}
// Required for the registrationError event.
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
[RNCPushNotificationIOS didFailToRegisterForRemoteNotificationsWithError:error];
}
// Required for localNotification event
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
didReceiveNotificationResponse:(UNNotificationResponse *)response
withCompletionHandler:(void (^)(void))completionHandler
{
[RNCPushNotificationIOS didReceiveNotificationResponse:response];
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.moduleName = @"myapp";
// You can add your custom initial props in the dictionary below.
// They will passed down toViewController used by React Native.
// Define UNUserNotificationCenter
UNUserNotificationCenter *center = [UNUserNotificationCenter
currentNotificationCenter];
center.delegate = self;
self.initialProps = @{};
[FIRApp configure];
return [super application:application didFinishLaunchingWithOptions:launchOptions];
}
//Called when a notification is delivered to a foreground app.
-(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler
{
completionHandler(UNNotificationPresentationOptionSound | UNNotificationPresentationOptionAlert | UNNotificationPresentationOptionBadge);
}
@end
make import
import PushNotificationIOS from '@react-native-community/push-notification-ios';
PushNotificationIOS.requestPermissions();
const pushNotificationList1: any = PushNotificationIOS.addEventListener('registrationError',
(registrationError) => {
console.log('PushNotificationIOS error ', registrationError)
});
const pushNotificationList2: any = PushNotificationIOS.addEventListener('register',
async (token) => {
// console.log('PushNotificationIOS token ========= ', token);
TencentImSDKPlugin?.v2TIMManager.setAPNSListener();
const setOfflinePushConfig = await TencentImSDKPlugin.v2TIMManager
.getOfflinePushManager()
.setOfflinePushConfig(15899, token, false); // 123456
if (setOfflinePushConfig.code === 0) {
console.log(' --------...==...------ ', setOfflinePushConfig);
}
});
const type = 'notification';
PushNotificationIOS.addEventListener(type, onRemoteNotification);
return () => {
PushNotificationIOS.removeEventListener(type);
pushNotificationList1?.remove();
pushNotificationList2?.remove();
};
Use businessid and token .
For Huawei
make import
import {
HmsPushInstanceId, HmsPushMessaging, HmsPushEvent, RNRemoteMessage,
} from "@hmscore/react-native-hms-push";
const HMSAvailability = await import('@hmscore/react-native-hms-availability');
//@ts-ignore
HMSAvailability.isHuaweiMobileServicesAvailable()
.then((res: any) => {
// console.log('noHMSAvailability ', JSON.stringify(res))
if (res != 1) {
Alert.alert('Huawai is service not working here');
}
})
.catch((err: any) => {
console.log('HMSAvailability error ', JSON.stringify(err)) });
let enableLogger = await HmsPushMessaging.enableLogger();
console.log('enableLogger--->>>>>>>>>', enableLogger);
HmsPushInstanceId.getToken("")
.then(async (result: any) => {
// console.log("[getToken] result===",JSON.stringify(result));
let token = result?.result;
console.log("[getToken] tok ===" + JSON.stringify(token));
const setOfflinePushConfig = await TencentImSDKPlugin.v2TIMManager
.getOfflinePushManager()
.setOfflinePushConfig(7575, token);
if (setOfflinePushConfig.code === 0) {
// console.log('0fflinePushConfigRes ',setOfflinePushConfig);
}
})
.catch((err) => {
console.log("Error/Exception: ",JSON.stringify(err));
});
HmsPushEvent.onTokenError((error: any) => {
console.log('onRemoteMessageReceived error ', error);
});
Use certificate id and token.
setOfflinePushConfig.code === 0 means deviceToken is saved successfully to TencentCloud.
react-native tencentcloud huawei fcm ios
Conclusion
With these steps, we've successfully integrated React Native with Tencent Cloud. Now your app is equipped to leverage powerful cloud services, such as cloud storage, databases, and authentication, all within the Tencent Cloud ecosystem.
Next Steps
Explore additional Tencent Cloud services that can further enhance your app, such as real-time messaging, push notifications, or serverless functions.
Consider implementing error handling and logging to monitor how your app interacts with the cloud in real-world scenarios.
Test your app thoroughly on different devices to ensure smooth performance across platforms.
If you run into any issues or have questions, feel free to leave a comment or check out the official Tencent Cloud SDK documentation for more details.
Final Thoughts
By combining React Native's flexibility with Tencent Cloud's robust infrastructure, you've set the foundation for a scalable, cloud-native mobile app. Keep experimenting, and let us know what you build!
Further Reading / Resources
Top comments (0)