DEV Community

Cover image for How to use Tencent Cloud in React Native, steps and code
faizullah
faizullah

Posted on

How to use Tencent Cloud in React Native, steps and code

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.

Image description

When login to Tenentcloud make an application that will be added in code.

  1. Goto Application management in Tenent Cloud im console.

  2. Press Create new app button and make app with folder name
    of app like myapp.

  3. 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

Image description

  1. Account management for myapp press

  2. Create new User and make it.

Access Settings

Image description

in console for myapp Access settings

  1. Add huawei configuration and get certificate ID that
    will be used with huawie device token (see huawei account config
    information below).

  2. Press Quick Configuration on right side new window appear
    that will show steps.

  3. Download timpush-configs.json file and place it in
    android/app/src/assets/htmal folder.

On press Next step add project configuration.

  1. Add Package Name , App ID , AppSecret from the huawei

Image description

  1. Add agconnect-services.json huawei to android/app folder.

then press Next step again

Image description

  1. Add implemention files to app level build.gradle file

  2. 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

Image description

  1. 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

Image description

  1. 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.

  2. From apple add KeyId

  3. Add TeamId also from apple acount

  4. Add app bundle id in the last.

Now testing the push

Get Certificate Id . Push apple token and bussness id (tencent user-id).

Image description

  1. To login from react native add user id that was created
    above

  2. Press Generate signature and get the token. use this token
    in react native to login tencentcloud to use services

  3. Paste the userSig

  4. Verify the user before use.

Push Test (Access Test)

Image description

  1. In tencent cloud im press Access Test

  2. Add user-id like 123456 and press get status see if the device
    is offline.

  3. Enter user-id press get token binding status button if the user
    device and token is available.

  4. Press send a push test button by selecting certificate id that
    are created above.

Huawei setup
Read below pages for help

https://developer.huawei.com/consumer/en/doc/AppGallery-connect-Guides/agc-get-started-reactnactive-0000001059210314

https://developer.huawei.com/consumer/en/doc/HMS-Plugin-Examples/reactnative-sample-code-0000001050157811-V1

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.

Image description

  1. Open My project in Huawei console

  2. Click My application

  3. Press new button and add myapp as android app

Image description

Download agconnect-services.json and add it to android/app folder

Image description

Add these line to android level build.gragle file

Image description

Add the above lines to app level build.gradle file.

Image description

  1. In My project select app in project settings

  2. myapp will be selected

  3. Select conventional

  4. Get developer id if needed

  5. In project get project id if required

  6. Set data center and get client id it will be used in tencent

  7. Client secret it will be used also in tencent

  8. Get api key if needed

  9. Download agconnect-services.json it will be place in project
    android/app/ folder if required again.

after there step perform below step

Image description

  1. Scroll down add sha26 key of your working machine

  2. Use Client Id and

  3. Client Secret for integration

Image description

  1. in push service open panel

  2. press Add push notification

Image description

  1. Fill the Message content (form)

  2. 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: () => { },
};
Enter fullscreen mode Exit fullscreen mode

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();
    }

  }
Enter fullscreen mode Exit fullscreen mode

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();
    }
  }
Enter fullscreen mode Exit fullscreen mode

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);
          }
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

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();
  };

Enter fullscreen mode Exit fullscreen mode

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);
          });

Enter fullscreen mode Exit fullscreen mode

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

Tencent Cloud React Native SDK Documentation

React Native Official Documentation

Top comments (0)