integration

The principle of

The environment

  • Node: v16.13.2
  • NPM: 8.1.2
  • Yarn: 1.22.17
  • React: 17.0.2
  • The react – native: 0.67.2,
  • The react — native code – push: ^ 7.0.4
  • Xcode: Version 13.2.1 (13C100)
  • Android Studio: Android Studio Bumblebee | 2021.1.1 Patch 1
  • Gradle: com. Android. Tools. Build: Gradle: 7.1.1

integration

Install the appcenter

npm install -g appcenter-cli
Copy the code

Operations related to AppCenter

The login operation

1. Enter the login command appCenter login in the terminal. After the login, the browser will automatically open and let you choose a login method

2. After login, a string of tokens will be generated and copied

Other commands
  • View the configuration:appcenter profile list
  • Log out:appcenter logout
  • View all login tokens:appcenter tokens list
  • Delete a token:appcenter tokens delete <machineName>

Used in ReactNative project

Create separate apps for iOS and Android

Run the following commands for different systems

appcenter apps create -d <appDisplayName> -o <operatingSystem>  -p <platform>
Copy the code

For example, run the following commands for iOS and Android

appcenter apps create -d RNDemoAndroid -o Android -p React-Native
appcenter apps create -d RNDemoiOS -o iOS -p React-Native
Copy the code

After creating apps in Appcenter, you need to create keys corresponding to the Staging and Production environments for each App

appcenter codepush deployment add -a <ownerName>/RNDemoiOS Staging
appcenter codepush deployment add -a <ownerName>/RNDemoiOS Production
Copy the code

note: Replace ownerName with your Appcenter username

Finally, we will get a total of four CodePush Deployment keys for iOS and Android groups, as shown in the figure below

The ReactNative project installs CodePush

CD to your ReactNative project directory and run the command

npm install --save react-native-code-push
Copy the code

Update iOS project in ReactNative

Install dependencies for iOS projects

Run CD ios && pod install && CD in the project directory.. Install the dependencies in the POD file and return to the project home directory

Use Xcode to open the.xcworkspace file in the ios home directory and edit Appdelegate.m

Introduce the CodePush header file

[[NSBundle mainBundle] URLForResource:@”main” WithexBundle :@” jsBundle “]; Return [CodePush bundleURL] instead;

As is shown in

IOS Multi-environment configuration

1. Create xcConfig files for the three environments

2. Write the Deployment keys corresponding to the stage and Production environments in CodePush to the corresponding files

3. Add a Stage environment configuration to the project (I Duplicate “Realse” directly) and select the corresponding XCconfig file for each environment, as shown in the figure4. Create a Scheme. You are advised to use Debug, Stage, Release, and then Edit Scheme to change the Buid Configuration of each environment to the corresponding value

5. Configuring multiple environments means more than that. You can set different AppIcon, certificate, name, and various custom variables for different environments, as shown in the figure

You can add user-defined constants for different project environments, but I won’t expand on that here.${RN_DEMO_CODE_PUSH_DEPLOYMENT_KEY} = ${RN_DEMO_CODE_PUSH_DEPLOYMENT_KEY}This completes the iOS multi-environment configuration

Android project modification in ReactNative

Modify Android/Settings. gradle by adding the following code

include ':app'.':react-native-code-push'
project(':react-native-code-push').projectDir = new File(rootProject.projectDir, '.. /node_modules/react-native-code-push/android/app')
Copy the code

Modify android/app/build. Gradle

Find apply from: “.. /.. /node_modules/react-native/react.gradle” is added below this line

apply from: ".. /.. /node_modules/react-native-code-push/android/codepush.gradle"
Copy the code

Modify the mainApplication. Java file

.// 1. Import the plugin class.
import com.microsoft.codepush.react.CodePush;
public class MainApplication extends Application implements ReactApplication {
    private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {...// 2. Override the getJSBundleFile method to let
        // the CodePush runtime determine where to get the JS
        // bundle location from on each app start
        @Override
        protected String getJSBundleFile(a) {
            returnCodePush.getJSBundleFile(); }}; }Copy the code

Android multi-environment Settings

Find the buildTypes code block in build.gradle(:app) and make the following changes

Replace <INSERT_STAGING_KEY> with your deploymentKey in codepush


buildTypes {
    debug {
        signingConfig signingConfigs.debug
        if (nativeArchitectures) {
            ndk {
                abiFilters nativeArchitectures.split(', ')}}// Note: CodePush updates shouldn't be tested in Debug mode as they're overriden by the RN packager. However, because CodePush checks for updates in all modes, we must supply a key.
        resValue "string"."CodePushDeploymentKey".'" "'
    }
    / / * * * * * * * * * * * * * * * * * * * * * * * * * * add code start * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
    releaseStaging {
        // Caution! In production, you need to generate your own keystore file.
        // see https://reactnative.dev/docs/signed-apk-android.
        signingConfig signingConfigs.archive
        minifyEnabled enableProguardInReleaseBuilds
        proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
        resValue "string"."CodePushDeploymentKey".'"<INSERT_STAGING_KEY>"'
        //https://stackoverflow.com/questions/52777665/react-native-code-push-unable-to-resolve-dependency-for-appreleasestaging -com
        // Add this or the runtime will report an error
        matchingFallbacks = ["release"]}/ / * * * * * * * * * * * * * * * * * * * * * * * * * * add code end * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
    release {
        // Caution! In production, you need to generate your own keystore file.
        // see https://reactnative.dev/docs/signed-apk-android.
        signingConfig signingConfigs.archive
        minifyEnabled enableProguardInReleaseBuilds
        proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
        resValue "string"."CodePushDeploymentKey".'"<INSERT_STAGING_KEY>"'}}Copy the code

ReactNative TS/JS code modification

When Code Push API is updated, the version judged is the version field at the top of package.json, and the version needs to be changed every time it is updated. As a demo, I directly modified the Code in app.tsx without creating a new component

const App = () = > {
  const isDarkMode = useColorScheme() === 'dark';
  
  const backgroundStyle = {
    backgroundColor: isDarkMode ? Colors.darker : Colors.lighter,
  };

  // Check the update method
  const checkForUpdate = () = > {
    CodePush.sync({
      installMode: CodePush.InstallMode.IMMEDIATE,
    },(status: CodePush.SyncStatus) = >{
      switch (status) {
        case CodePush.SyncStatus.UP_TO_DATE:{
          Alert.alert("Tip"."This is the latest version.")}break;
        case CodePush.SyncStatus.UPDATE_INSTALLED:{
          Alert.alert("Tip"."Latest version installed")}break;

        default:
        break
      }
      
      console.log(status)
    },() = >{}); };// Clear the update
  const clear = () = > {
    CodePush.clearUpdates();
  };
  var name = packageInfo.name;
  var version = packageInfo.version;
  return (
    <SafeAreaView style={backgroundStyle}>
      <StatusBar barStyle={isDarkMode ? 'light-content' : 'dark-content'} / >
      <ScrollView
        contentInsetAdjustmentBehavior="automatic"
        style={backgroundStyle}>
        <Header />
        <View
          style={{
            backgroundColor: isDarkMode ? Colors.black : Colors.white,
          }}>
          <Section title="Project Name">
            <Text style={styles.highlight}>{name}</Text>  
          </Section>
          <Section title="Version Number">
            <Text style={styles.highlight}>{version}</Text>
          </Section>
          <Section title="Version Info">
            <Button title='Check for updates' onPress={checkForUpdate}/>
            <Button title='Clear updates' onPress={clear}/>
          </Section>
        </View>
      </ScrollView>
    </SafeAreaView>
  );
};

Copy the code

Packaged bundle

Change the version number corresponding to version in package.json and run the command to package jsbundle for iOS

appcenter codepush release-react -a [email protected]/RNDemoiOS
Copy the code

Results the following

Before the update

After the update