Skip to content

Instantly share code, notes, and snippets.

@hungvu193
Last active October 15, 2018 08:57
Show Gist options
  • Save hungvu193/0971e5628735f98ffe0c9b22c2b67cf3 to your computer and use it in GitHub Desktop.
Save hungvu193/0971e5628735f98ffe0c9b22c2b67cf3 to your computer and use it in GitHub Desktop.
CodePush Docs

CodePush Document

Getting started

Once you've followed the general-purpose "getting started" instructions for setting up your CodePush account, you can start CodePush-ifying your React Native app by running the following command from within your app's root directory:

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

As with all other React Native plugins, the integration experience is different for iOS and Android, so perform the following setup steps depending on which platform(s) you are targeting. Note, if you are targeting both platforms it is recommended to create separate CodePush applications for each platform.

If you want to see how other projects have integrated with CodePush, you can check out the excellent example apps provided by the community. Additionally, if you'd like to quickly familiarize yourself with CodePush + React Native, you can check out the awesome getting started videos produced by Bilal Budhani and/or Deepak Sisodiya .

NOTE: This guide assumes you have used the react-native init command to initialize your React Native project. As of March 2017, the command create-react-native-app can also be used to initialize a React Native project. If using this command, please run npm run eject in your project's home directory to get a project very similar to what react-native init would have created.

Setup:

Android

In order to integrate CodePush into your Android project, please perform the following steps:

Plugin Installation (Android)

In order to accommodate as many developer preferences as possible, the CodePush plugin supports Android installation via two mechanisms:

  1. RNPM - React Native Package Manager (RNPM) is an awesome tool that provides the simplest installation experience possible for React Native plugins. If you're already using it, or you want to use it, then we recommend this approach.

  2. "Manual" - If you don't want to depend on any additional tools or are fine with a few extra installation steps (it's a one-time thing), then go with this approach.

*Note: Due to a code change from the React Native repository, if your installed React Native version ranges from 0.29 to 0.32, we recommend following the manual steps to set up correctly. *

Plugin Installation (Android - RNPM)

  1. As of v0.27 of React Native, rnpm link has already been merged into the React Native CLI. Simply run:

    react-native link react-native-code-push
    

    If your app uses a version of React Native that is lower than v0.27, run the following:

    rnpm link react-native-code-push
    

    Note: If you don't already have RNPM installed, you can do so by simply running npm i -g rnpm and then executing the above command.

  2. If you're using RNPM >=1.6.0, you will be prompted for the deployment key you'd like to use. If you don't already have it, you can retreive this value by running code-push deployment ls <appName> -k, or you can choose to ignore it (by simply hitting <ENTER>) and add it in later. To get started, we would recommend just using your Staging deployment key, so that you can test out the CodePush end-to-end.

And that's it for installation using RNPM! Continue below to the Plugin Configuration section to complete the setup.

Plugin Installation (Android - Manual)

  1. In your android/settings.gradle file, make the following additions:

    include ':app', ':react-native-code-push'
    project(':react-native-code-push').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-code-push/android/app')
  2. In your android/app/build.gradle file, add the :react-native-code-push project as a compile-time dependency:

    ...
    dependencies {
        ...
        compile project(':react-native-code-push')
    }
  3. In your android/app/build.gradle file, add the codepush.gradle file as an additional build task definition underneath react.gradle:

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

Plugin Configuration (Android)

NOTE: If you used RNPM or react-native link to automatically link the plugin, these steps have already been done for you so you may skip this section.

After installing the plugin and syncing your Android Studio project with Gradle, you need to configure your app to consult CodePush for the location of your JS bundle, since it will "take control" of managing the current and all future versions. To do this:

For React Native >= v0.29

For newly created React Native application

If you are integrating Code Push into React Native application please do the following steps:

Update the MainApplication.java file to use CodePush via the following changes:

...
// 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 in order to let
        // the CodePush runtime determine where to get the JS
        // bundle location from on each app start
        @Override
        protected String getJSBundleFile() {
            return CodePush.getJSBundleFile();
        }

        @Override
        protected List<ReactPackage> getPackages() {
            // 3. Instantiate an instance of the CodePush runtime and add it to the list of
            // existing packages, specifying the right deployment key. If you don't already
            // have it, you can run "code-push deployment ls <appName> -k" to retrieve your key.
            return Arrays.<ReactPackage>asList(
                new MainReactPackage(),
                new CodePush("deployment-key-here", MainApplication.this, BuildConfig.DEBUG)
            );
        }
    };
}

NOTE: For React Native v0.49+ please be sure that getJSMainModuleName function in the MainApplication.java file determines correct URL to fetch JS bundle (used when dev support is enabled, see this for more details) e.g.

@Override
protected String getJSMainModuleName() {
    return "index";
}
For existing native application

If you are integrating React Native into existing native application please do the following steps:

Update MyReactActivity.java (it could be named differently in your app) file to use CodePush via the following changes:

...
// 1. Import the plugin class.
import com.microsoft.codepush.react.CodePush;

public class MyReactActivity extends Activity {
    private ReactRootView mReactRootView;
    private ReactInstanceManager mReactInstanceManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        ...
        mReactInstanceManager = ReactInstanceManager.builder()
                // ...
                // Add CodePush package
                .addPackage(new CodePush("deployment-key-here", getApplicationContext(), BuildConfig.DEBUG))
                // Get the JS Bundle File via Code Push
                .setJSBundleFile(CodePush.getJSBundleFile())
                // ...
                
                .build();
        mReactRootView.startReactApplication(mReactInstanceManager, "MyReactNativeApp", null);

        setContentView(mReactRootView);
    }

    ...
}

For React Native v0.19 - v0.28

Update the MainActivity.java file to use CodePush via the following changes:

...
// 1. Import the plugin class (if you used RNPM to install the plugin, this
// should already be done for you automatically so you can skip this step).
import com.microsoft.codepush.react.CodePush;

public class MainActivity extends ReactActivity {
    // 2. Override the getJSBundleFile method in order to let
    // the CodePush runtime determine where to get the JS
    // bundle location from on each app start
    @Override
    protected String getJSBundleFile() {
        return CodePush.getJSBundleFile();
    }

    @Override
    protected List<ReactPackage> getPackages() {
        // 3. Instantiate an instance of the CodePush runtime and add it to the list of
        // existing packages, specifying the right deployment key. If you don't already
        // have it, you can run "code-push deployment ls <appName> -k" to retrieve your key.
        return Arrays.<ReactPackage>asList(
            new MainReactPackage(),
            new CodePush("deployment-key-here", this, BuildConfig.DEBUG)
        );
    }

    ...
}

Background React Instances

This section is only necessary if you're explicitly launching a React Native instance without an Activity (for example, from within a native push notification receiver). For these situations, CodePush must be told how to find your React Native instance.

In order to update/restart your React Native instance, CodePush must be configured with a ReactInstanceHolder before attempting to restart an instance in the background. This is usually done in your Application implementation.

For React Native >= v0.29 (Background React Instances)

Update the MainApplication.java file to use CodePush via the following changes:

...
// 1. Declare your ReactNativeHost to extend ReactInstanceHolder. ReactInstanceHolder is a subset of ReactNativeHost, so no additional implementation is needed.
import com.microsoft.codepush.react.ReactInstanceHolder;

public class MyReactNativeHost extends ReactNativeHost implements ReactInstanceHolder {
  // ... usual overrides
}

// 2. Provide your ReactNativeHost to CodePush.

public class MainApplication extends Application implements ReactApplication {

   private final MyReactNativeHost mReactNativeHost = new MyReactNativeHost(this);

   @Override
   public void onCreate() {
     CodePush.setReactInstanceHolder(mReactNativeHost);
     super.onCreate();
  }
}
For React Native v0.19 - v0.28 (Background React Instances)

Before v0.29, React Native did not provide a ReactNativeHost abstraction. If you're launching a background instance, you'll likely have built your own, which should now implement ReactInstanceHolder. Once that's done:

// 1. Provide your ReactInstanceHolder to CodePush.

public class MainApplication extends Application {

   @Override
   public void onCreate() {
     // ... initialize your instance holder
     CodePush.setReactInstanceHolder(myInstanceHolder);
     super.onCreate();
  }
}

In order to effectively make use of the Staging and Production deployments that were created along with your CodePush app, refer to the multi-deployment testing docs below before actually moving your app's usage of CodePush into production.

WIX React Native Navigation applications

If you are using WIX React Native Navigation version 1.x based application, please do the following steps to integrate CodePush:

  1. No need to change MainActivity.java file, so if you are integrating CodePush to newly created RNN application it might be looking like this:
import com.facebook.react.ReactActivity;
import com.reactnativenavigation.controllers.SplashActivity;

public class MainActivity extends SplashActivity {

}
  1. Update the MainApplication.java file to use CodePush via the following changes:
// ...
import com.facebook.react.ReactInstanceManager;

// Add CodePush imports
import com.microsoft.codepush.react.ReactInstanceHolder;
import com.microsoft.codepush.react.CodePush;

public class MainApplication extends NavigationApplication implements ReactInstanceHolder {

	@Override
	public boolean isDebug() {
		// Make sure you are using BuildConfig from your own application
		return BuildConfig.DEBUG;
	}

	protected List<ReactPackage> getPackages() {
		// Add additional packages you require here
		return Arrays.<ReactPackage>asList(
			new CodePush("deployment-key-here", getApplicationContext(), BuildConfig.DEBUG)
		);
	}

	@Override
	public List<ReactPackage> createAdditionalReactPackages() {
		return getPackages();
	}

	@Override
	public String getJSBundleFile() {
        // Override default getJSBundleFile method with the one CodePush is providing
		return CodePush.getJSBundleFile();
	}

	@Override
	public String getJSMainModuleName() {
		return "index";
	}

    @Override
    public ReactInstanceManager getReactInstanceManager() {
        // CodePush must be told how to find React Native instance
        return getReactNativeHost().getReactInstanceManager();
    }
}

If you are using WIX React Native Navigation version 2.x based application, please do the following steps to integrate CodePush:

  1. As per React Native Navigation's documentation, MainActivity.java should extend NavigationActivity, no changes required to incorporate CodePush:
import com.reactnativenavigation.NavigationActivity;

public class MainActivity extends NavigationActivity {

}
  1. Update the MainApplication.java file to use CodePush via the following changes:
// ...
import com.facebook.react.ReactInstanceManager;

// Add CodePush imports
import com.microsoft.codepush.react.CodePush;

public class MainApplication extends NavigationApplication {

    @Override
    public boolean isDebug() {
        return BuildConfig.DEBUG;
    }

    @Override
    protected ReactGateway createReactGateway() {
        ReactNativeHost host = new NavigationReactNativeHost(this, isDebug(), createAdditionalReactPackages()) {
            @javax.annotation.Nullable
            @Override
            protected String getJSBundleFile() {
                return CodePush.getJSBundleFile();
            }
            
        };
        return new ReactGateway(this, isDebug(), host);
    }

    @Override
    public List<ReactPackage> createAdditionalReactPackages() {
        return Arrays.<ReactPackage>asList(
	    new CodePush("deployment-key-here", getApplicationContext(), isDebug())
	    //,MainReactPackage , etc...
    }
}

Code Signing setup

Starting with CLI version 2.1.0 you can self sign bundles during release and verify its signature before installation of update. For more info about Code Signing please refer to relevant code-push documentation section. In order to use Public Key for Code Signing you need to do following steps:

  1. Add CodePushPublicKey string item to /path_to_your_app/android/app/src/main/res/values/strings.xml. It may looks like this:
<resources>
   <string name="app_name">my_app</string>
   <string name="CodePushPublicKey">-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAtPSR9lkGzZ4FR0lxF+ZA
P6jJ8+Xi5L601BPN4QESoRVSrJM08roOCVrs4qoYqYJy3Of2cQWvNBEh8ti3FhHu
tiuLFpNdfzM4DjAw0Ti5hOTfTixqVBXTJPYpSjDh7K6tUvp9MV0l5q/Ps3se1vud
M1/X6g54lIX/QoEXTdMgR+SKXvlUIC13T7GkDHT6Z4RlwxkWkOmf2tGguRcEBL6j
ww7w/3g0kWILz7nNPtXyDhIB9WLH7MKSJWdVCZm+cAqabUfpCFo7sHiyHLnUxcVY
OTw3sz9ceaci7z2r8SZdsfjyjiDJrq69eWtvKVUpredy9HtyALtNuLjDITahdh8A
zwIDAQAB
-----END PUBLIC KEY-----</string>
</resources>
  1. Configure CodePush instance to use this parameter
  • using constructor
new CodePush(
    "deployment-key",
    getApplicationContext(),
    BuildConfig.DEBUG,
    R.string.CodePushPublicKey)

or

  • using builder
new CodePushBuilder("deployment-key-here",getApplicationContext())
   .setIsDebugMode(BuildConfig.DEBUG)
   .setPublicKeyResourceDescriptor(R.string.CodePushPublicKey)
   .build()

iOS

Once you've acquired the CodePush plugin, you need to integrate it into the Xcode project of your React Native app and configure it correctly. To do this, take the following steps:

Plugin Installation (iOS)

In order to accommodate as many developer preferences as possible, the CodePush plugin supports iOS installation via three mechanisms:

  1. RNPM - React Native Package Manager (RNPM) is an awesome tool that provides the simplest installation experience possible for React Native plugins. If you're already using it, or you want to use it, then we recommend this approach.

  2. CocoaPods - If you're building a native iOS app that is embedding React Native into it, or you simply prefer using CocoaPods, then we recommend using the Podspec file that we ship as part of our plugin.

  3. "Manual" - If you don't want to depend on any additional tools or are fine with a few extra installation steps (it's a one-time thing), then go with this approach.

Plugin Installation (iOS - RNPM)

  1. As of v0.27 of React Native, rnpm link has already been merged into the React Native CLI. Simply run:

    react-native link react-native-code-push
    

    If your app uses a version of React Native that is lower than v0.27, run the following:

    rnpm link react-native-code-push
    

    Note: If you don't already have RNPM installed, you can do so by simply running npm i -g rnpm and then executing the above command. If you already have RNPM installed, make sure you have v1.9.0+ in order to benefit from this one step install.

  2. You will be prompted for the deployment key you'd like to use. If you don't already have it, you can retrieve this value by running code-push deployment ls <appName> -k, or you can choose to ignore it (by simply hitting <ENTER>) and add it in later. To get started, we would recommend just using your Staging deployment key, so that you can test out the CodePush end-to-end.

And that's it! Isn't RNPM awesome? :)

Plugin Installation (iOS - CocoaPods)

  1. Add the ReactNative and CodePush plugin dependencies to your Podfile, pointing at the path where NPM installed it

    # React Native requirements
    pod 'React', :path => '../node_modules/react-native', :subspecs => [
       'Core',
       'CxxBridge', # Include this for RN >= 0.47
       'DevSupport', # Include this to enable In-App Devmenu if RN >= 0.43
       'RCTText',
       'RCTNetwork',
       'RCTWebSocket', # Needed for debugging
       'RCTAnimation', # Needed for FlatList and animations running on native UI thread
       # Add any other subspecs you want to use in your project
    ]
    # Explicitly include Yoga if you are using RN >= 0.42.0
    pod 'yoga', :path => '../node_modules/react-native/ReactCommon/yoga'
    pod 'DoubleConversion', :podspec => '../node_modules/react-native/third-party-podspecs/DoubleConversion.podspec'
    pod 'glog', :podspec => '../node_modules/react-native/third-party-podspecs/glog.podspec'
    pod 'Folly', :podspec => '../node_modules/react-native/third-party-podspecs/Folly.podspec'
      
    # CodePush plugin dependency
    pod 'CodePush', :path => '../node_modules/react-native-code-push'
    

    NOTE: The above path needs to be relative to your app's Podfile, so adjust it as necessary.

    NOTE: JWT library should be >= version 3.0.x

  2. Run pod install

NOTE: The CodePush .podspec depends on the React pod, and so in order to ensure that it can correctly use the version of React Native that your app is built with, please make sure to define the React dependency in your app's Podfile as explained here.

Plugin Installation (iOS - Manual)

  1. Open your app's Xcode project

  2. Find the CodePush.xcodeproj file within the node_modules/react-native-code-push/ios directory (or node_modules/react-native-code-push for <=1.7.3-beta installations) and drag it into the Libraries node in Xcode

    Add CodePush to project

  3. Select the project node in Xcode and select the "Build Phases" tab of your project configuration.

  4. Drag libCodePush.a from Libraries/CodePush.xcodeproj/Products into the "Link Binary With Libraries" section of your project's "Build Phases" configuration.

    Link CodePush during build

  5. Click the plus sign underneath the "Link Binary With Libraries" list and select the libz.tbd library underneath the iOS 9.1 node.

    Libz reference

    Note: Alternatively, if you prefer, you can add the -lz flag to the Other Linker Flags field in the Linking section of the Build Settings.

Plugin Configuration (iOS)

NOTE: If you used RNPM or react-native link to automatically link the plugin, these steps have already been done for you so you may skip this section.

Once your Xcode project has been setup to build/link the CodePush plugin, you need to configure your app to consult CodePush for the location of your JS bundle, since it is responsible for synchronizing it with updates that are released to the CodePush server. To do this, perform the following steps:

  1. Open up the AppDelegate.m file, and add an import statement for the CodePush headers:

    #import <CodePush/CodePush.h>
  2. Find the following line of code, which loads your JS Bundle from the app binary for production releases:

    jsCodeLocation = [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"];
  3. Replace it with this line:

    jsCodeLocation = [CodePush bundleURL];

This change configures your app to always load the most recent version of your app's JS bundle. On the first launch, this will correspond to the file that was compiled with the app. However, after an update has been pushed via CodePush, this will return the location of the most recently installed update.

NOTE: The bundleURL method assumes your app's JS bundle is named main.jsbundle. If you have configured your app to use a different file name, simply call the bundleURLForResource: method (which assumes you're using the .jsbundle extension) or bundleURLForResource:withExtension: method instead, in order to overwrite that default behavior

Typically, you're only going to want to use CodePush to resolve your JS bundle location within release builds, and therefore, we recommend using the DEBUG pre-processor macro to dynamically switch between using the packager server and CodePush, depending on whether you are debugging or not. This will make it much simpler to ensure you get the right behavior you want in production, while still being able to use the Chrome Dev Tools, live reload, etc. at debug-time.

For React Native 0.49 and above:

NSURL *jsCodeLocation;

#ifdef DEBUG
    jsCodeLocation = [NSURL URLWithString:@"http://localhost:8081/index.bundle?platform=ios&dev=true"];
#else
    jsCodeLocation = [CodePush bundleURL];
#endif

For React Native 0.48 and below:

NSURL *jsCodeLocation;

#ifdef DEBUG
    jsCodeLocation = [NSURL URLWithString:@"http://localhost:8081/index.ios.bundle?platform=ios&dev=true"];
#else
    jsCodeLocation = [CodePush bundleURL];
#endif

To let the CodePush runtime know which deployment it should query for updates against, open your app's Info.plist file and add a new entry named CodePushDeploymentKey, whose value is the key of the deployment you want to configure this app against (e.g. the key for the Staging deployment for the FooBar app). You can retrieve this value by running code-push deployment ls <appName> -k in the CodePush CLI (the -k flag is necessary since keys aren't displayed by default) and copying the value of the Deployment Key column which corresponds to the deployment you want to use (see below). Note that using the deployment's name (e.g. Staging) will not work. That "friendly name" is intended only for authenticated management usage from the CLI, and not for public consumption within your app.

Deployment list

In order to effectively make use of the Staging and Production deployments that were created along with your CodePush app, refer to the multi-deployment testing docs below before actually moving your app's usage of CodePush into production.

HTTP exception domains configuration (iOS)

CodePush plugin makes HTTPS requests to the following domains:

  • codepush.azurewebsites.net
  • codepush.blob.core.windows.net
  • codepushupdates.azureedge.net

If you want to change the default HTTP security configuration for any of these domains, you have to define the NSAppTransportSecurity (ATS) configuration inside your Info.plist file:

<plist version="1.0">
  <dict>
    <!-- ...other configs... -->

    <key>NSAppTransportSecurity</key>
    <dict>
      <key>NSExceptionDomains</key>
      <dict>
        <key>codepush.azurewebsites.net</key>
        <dict><!-- read the ATS Apple Docs for available options --></dict>
      </dict>
    </dict>

    <!-- ...other configs... -->
  </dict>
</plist>

Before doing anything, please read the docs first.

Code Signing setup

Starting with CLI version 2.1.0 you can self sign bundles during release and verify its signature before installation of update. For more info about Code Signing please refer to relevant code-push documentation section.

In order to configure Public Key for bundle verification you need to add record in Info.plist with name CodePushPublicKey and string value of public key content. Example:

<plist version="1.0">
  <dict>
    <!-- ...other configs... -->

    <key>CodePushPublicKey</key>
        <string>-----BEGIN PUBLIC KEY-----
MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBANkWYydPuyOumR/sn2agNBVDnzyRpM16NAUpYPGxNgjSEp0etkDNgzzdzyvyl+OsAGBYF3jCxYOXozum+uV5hQECAwEAAQ==
-----END PUBLIC KEY-----</string>

    <!-- ...other configs... -->
  </dict>
</plist>

Sometimes react-native link react-native-code-push will not work perfectly, if you have any problems while setup CodePush please try install it manually.(high recommended)

Multi-Deployment Testing (Recommended):

If you want to be able to install both debug and release builds simultaneously on the same device (highly recommended!), then you need to ensure that your debug build has a unique identity and icon from your release build. Otherwise, neither the OS nor you will be able to differentiate between the two. Like Debug, Development, Staging and Release. You can achieve this by performing the following steps:

Android

NOTE

Complete demo configured with "multi-deployment testing" feature is here.

The Android Gradle plugin allows you to define custom config settings for each "build type" (e.g. debug, release), which in turn are generated as properties on the BuildConfig class that you can reference from your Java code. This mechanism allows you to easily configure your debug builds to use your CodePush staging deployment key and your release builds to use your CodePush production deployment key.

To set this up, perform the following steps:

  1. Open your app's build.gradle file (e.g. android/app/build.gradle in standard React Native projects)

  2. Find the android { buildTypes {} } section and define buildConfigField entries for both your debug and release build types, which reference your Staging and Production deployment keys respectively. If you prefer, you can define the key literals in your gradle.properties file, and then reference them here. Either way will work, and it's just a matter of personal preference.

    android {
        ...
        buildTypes {
            debug {
                ...
                // Note: CodePush updates should not be tested in Debug mode as they are overriden by the RN packager. However, because CodePush checks for updates in all modes, we must supply a key.
                buildConfigField "String", "CODEPUSH_KEY", '""'
                ...
            }
    
            releaseStaging {
                ...
                buildConfigField "String", "CODEPUSH_KEY", '"<INSERT_STAGING_KEY>"'
                ...
            }
    
            release {
                ...
                buildConfigField "String", "CODEPUSH_KEY", '"<INSERT_PRODUCTION_KEY>"'
                ...
            }
        }
        ...
    }

    NOTE: As a reminder, you can retrieve these keys by running code-push deployment ls <APP_NAME> -k from your terminal.

    NOTE: The naming convention for releaseStaging is significant due to this line.

  3. Pass the deployment key to the CodePush constructor via the build config you just defined, as opposed to a string literal.

For React Native >= v0.29

Open up your MainApplication.java file and make the following changes:

@Override
protected List<ReactPackage> getPackages() {
    return Arrays.<ReactPackage>asList(
        ...
        new CodePush(BuildConfig.CODEPUSH_KEY, MainApplication.this, BuildConfig.DEBUG), // Add/change this line.
        ...
    );
}

For React Native v0.19 - v0.28

Open up your MainActivity.java file and make the following changes:

@Override
protected List<ReactPackage> getPackages() {
    return Arrays.<ReactPackage>asList(
        ...
        new CodePush(BuildConfig.CODEPUSH_KEY, this, BuildConfig.DEBUG), // Add/change this line.
        ...
    );
}

Note: If you gave your build setting a different name in your Gradle file, simply make sure to reflect that in your Java code.

And that's it! Now when you run or build your app, your debug builds will automatically be configured to sync with your Staging deployment, and your release builds will be configured to sync with your Production deployment.

NOTE: By default, the react-native run-android command builds and deploys the debug version of your app, so if you want to test out a release/production build, simply run `react-native run-android --variant release. Refer to the React Native docs for details about how to configure and create release builds for your Android apps.

If you want to be able to install both debug and release builds simultaneously on the same device (highly recommended!), then you need to ensure that your debug build has a unique identity and icon from your release build. Otherwise, neither the OS nor you will be able to differentiate between the two. You can achieve this by performing the following steps:

  1. In your build.gradle file, specify the applicationIdSuffix field for your debug build type, which gives your debug build a unique identity for the OS (e.g. com.foo vs. com.foo.debug).
buildTypes {
    debug {
        applicationIdSuffix ".debug"
    }
}
  1. Create the app/src/debug/res directory structure in your app, which allows overriding resources (e.g. strings, icons, layouts) for your debug builds

  2. Create a values directory underneath the debug res directory created in #2, and copy the existing strings.xml file from the app/src/main/res/values directory

  3. Open up the new debug strings.xml file and change the <string name="app_name"> element's value to something else (e.g. foo-debug). This ensures that your debug build now has a distinct display name, so that you can differentiate it from your release build.

  4. Optionally, create "mirrored" directories in the app/src/debug/res directory for all of your app's icons that you want to change for your debug build. This part isn't technically critical, but it can make it easier to quickly spot your debug builds on a device if its icon is noticeable different.

And that's it! View here for more details on how resource merging works in Android.

IOS

NOTE

Complete demos configured with "multi-deployment testing" feature are [here]:

  • without using cocoa pods: link
  • using cocoa pods: link

Xcode allows you to define custom build settings for each "configuration" (e.g. debug, release), which can then be referenced as the value of keys within the Info.plist file (e.g. the CodePushDeploymentKey setting). This mechanism allows you to easily configure your builds to produce binaries, which are configured to synchronize with different CodePush deployments.

To set this up, perform the following steps:

  1. Open up your Xcode project and select your project in the Project navigator window

  2. Ensure the project node is selected, as opposed to one of your targets

  3. Select the Info tab

  4. Click the + button within the Configurations section and select Duplicate "Release" Configuration

    Configuration

  5. Name the new configuration Staging (or whatever you prefer)

  6. Select the Build Settings tab

  7. Go to Build Location -> Per-configuration Build Products Path -> Staging and change Staging value from $(BUILD_DIR)/$(CONFIGURATION)$(EFFECTIVE_PLATFORM_NAME) to $(BUILD_DIR)/Release$(EFFECTIVE_PLATFORM_NAME)

    BuildFilesPath

    NOTE: Due to facebook/react-native#11813, we have to do this step to make it possible to use other configurations than Debug or Release on RN 0.40.0 or higher.

  8. Click the + button on the toolbar and select Add User-Defined Setting

    Setting

  9. Name this new setting something like CODEPUSH_KEY, expand it, and specify your Staging deployment key for the Staging config and your Production deployment key for the Release config.

    Setting Keys

    NOTE: As a reminder, you can retrieve these keys by running code-push deployment ls <APP_NAME> -k from your terminal.

  10. Open your project's Info.plist file and change the value of your CodePushDeploymentKey entry to $(CODEPUSH_KEY)

    Infoplist

And that's it! Now when you run or build your app, your staging builds will automatically be configured to sync with your Staging deployment, and your release builds will be configured to sync with your Production deployment.

NOTE: CocoaPods users may need to run pod install before building with their new release configuration.

Note: If you encounter the error message ld: library not found for ..., please consult this issue for a possible solution.

Additionally, if you want to give them seperate names and/or icons, you can modify the Product Bundle Identifier, Product Name and Asset Catalog App Icon Set Name build settings, which will allow your staging builds to be distinguishable from release builds when installed on the same device.

*NOTE: In IOS after you create a new scheme, when you build your project in XCode, you will see a lot of error because react native can't not link your scheme that you have created before so you need react-native-schemes-manager to config your scheme by follow this link or this tutorial

In Nr-app we have 4 environment (Debug, Development, Staging, Release), every environments have a CodePushKey, CodePush will update your application depend on your CodePushKey, and when user open the app, CodePush will check the CodePushKey to download the update and when user restart the app or open it on next times, Latest update will be applied. There 's a big problem here, everytime you restart your application, even when you change somethings CodePush will rollback or update to latest version that you released before. The solution is Debug environment will not have a CodePushKey.

    //Example : Android build.gradle config for Multi-Deployment Testing
    buildTypes {
        release {
            signingConfig signingConfigs.release
            minifyEnabled enableProguardInReleaseBuilds
            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
            buildConfigField "String", "CODEPUSH_KEY", '"4hVYJB2jrW9LCAdasdaZrECci-QEpH8H5a4ed1e41-23f2-435b-bdb3-df42fe8a99f8"'
        }

        debug {
           applicationIdSuffix ".debug"
            // Note: CodePush updates should not be tested in Debug mode as they are overriden by the RN packager. However, because CodePush checks for updates in all modes, we must supply a key.
            buildConfigField "String", "CODEPUSH_KEY", '""'

        }

        development {
            applicationIdSuffix ".development"
            minifyEnabled enableProguardInReleaseBuilds
            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
            signingConfig signingConfigs.release
            buildConfigField "String", "CODEPUSH_KEY", '"r9KFsozjqe8uYYUBNvfafafbZBHBNzVHda4ed1e41-23f2-435b-bdb3-df42fe8a99f8"'

        }

        staging {
            applicationIdSuffix ".staging"
            minifyEnabled enableProguardInReleaseBuilds
            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
            signingConfig signingConfigs.release
            buildConfigField "String", "CODEPUSH_KEY", '"1DZvd63MEv8ScMCdsadasU0UoW5EEtl6lwa4ed1e41-23f2-435b-bdb3-df42fe8a99f8"'
        }

    }

When you run your application in debug environment, CodePush won't rollback or update your application because it can't find the CodePushKey. So we can use :

  • Debug : For coding like manual
  • Development : Release your change to development version and testing .
  • Staging(Pre-Production) : Release your change to Staging version and testing pre-production.
  • Production: After test your development and Staging version, if everything work perfectly, you can releasing your change to the AppStore(PlayStore).

Dynamic Deployment Assignment

The above section illustrated how you can leverage multiple CodePush deployments in order to effectively test your updates before broadly releasing them to your end users. However, since that workflow statically embeds the deployment assignment into the actual binary, a staging or production build will only ever sync updates from that deployment. In many cases, this is sufficient, since you only want your team, customers, stakeholders, etc. to sync with your pre-production releases, and therefore, only they need a build that knows how to sync with staging. However, if you want to be able to perform A/B tests, or provide early access of your app to certain users, it can prove very useful to be able to dynamically place specific users (or audiences) into specific deployments at runtime.

In order to achieve this kind of workflow, all you need to do is specify the deployment key you want the current user to syncronize with when calling the codePush method. When specified, this key will override the "default" one that was provided in your app's Info.plist (iOS) or MainActivity.java (Android) files. This allows you to produce a build for staging or production, that is also capable of being dynamically "redirected" as needed.

// Imagine that "userProfile" is a prop that this component received
// which includes the deployment key that the current user should use.
codePush.sync({ deploymentKey: userProfile.CODEPUSH_KEY });

With that change in place, now it's just a matter of choosing how your app determines the right deployment key for the current user. In practice, there are typically two solutions for this:

  1. Expose a user-visible mechanism for changing deployments at any time. For example, your settings page could have a toggle for enabling "beta" access. This model works well if you're not concerned with the privacy of your pre-production updates, and you have power users that may want to opt-in to earlier (and potentially buggy) updates at their own will (kind of like Chrome channels). However, this solution puts the decision in the hands of your users, which doesn't help you perform A/B tests transparently.

  2. Annotate the server-side profile of your users with an additional piece of metadata which indicates the deployment they should sync with. By default, your app could just use the binary-embedded key, but after a user has authenticated, your server can choose to "redirect" them to a different deployment, which allows you to incrementally place certain users or groups in different deployments as needed. You could even choose to store the server-response in local storage so that it becomes the new default. How you store the key alongside your user's profiles is entirely up to your authentication solution (e.g. Auth0, Firebase, custom DB + REST API), but is generally pretty trivial to do.

NOTE: If needed, you could also implement a hybrid solution that allowed your end-users to toggle between different deployments, while also allowing your server to override that decision. This way, you have a hierarchy of "deployment resolution" that ensures your app has the ability to update itself out-of-the-box, your end users can feel rewarded by getting early access to bits, but you also have the ability to run A/B tests on your users as needed.

Since we recommend using the Staging deployment for pre-release testing of your updates (as explained in the previous section), it doesn't neccessarily make sense to use it for performing A/B tests on your users, as opposed to allowing early-access (as explained in option #1 above). Therefore, we recommend making full use of custom app deployments, so that you can segment your users however makes sense for your needs. For example, you could create long-term or even one-off deployments, release a variant of your app to it, and then place certain users into it in order to see how they engage.

// #1) Create your new deployment to hold releases of a specific app variant
code-push deployment add [APP_NAME] test-variant-one

// #2) Target any new releases at that custom deployment
code-push release-react [APP_NAME] ios -d test-variant-one

NOTE: The total user count that is reported in your deployment's "Install Metrics" will take into account users that have "switched" from one deployment to another. For example, if your Production deployment currently reports having 1 total user, but you dynamically switch that user to Staging, then the Production deployment would report 0 total users, while Staging would report 1 (the user that just switched). This behavior allows you to accurately track your release adoption, even in the event of using a runtime-based deployment redirection solution.

Releasing:

Once your app has been configured and distributed to your users, and you've made some JS and/or asset changes, it's time to instantly release them! The simplest (and recommended) way to do this is to use the release-react command in the CodePush CLI, which will handle bundling your JavaScript and asset files and releasing the update to the CodePush server. In it's most basic form, this command only requires two parameters: your app name and the platform you are bundling the update for (either ios or android).

code-push release-react <appName> <platform> -d <Environment>
code-push release-react yper.sudev/nr-ios ios -k private.pem -d Development
code-push release-react yper.sudev/nr-android android -k private.pem -d Development
code-push release-react yper.sudev/nr-ios ios -k private.pem -d Production

The release-react command enables such a simple workflow because it provides many sensible defaults (e.g. generating a release bundle, assuming your app's entry file on iOS is either index.ios.js or index.js). However, all of these defaults can be customized to allow incremental flexibility as necessary, which makes it a good fit for most scenarios.

# Release a mandatory update with a changelog
code-push release-react MyApp-iOS ios -m --description "Modified the header color"

# Release an update for an app that uses a non-standard entry file name, and also capture
# the sourcemap file generated by react-native bundle
code-push release-react MyApp-iOS ios --entryFile MyApp.js --sourcemapOutput ../maps/MyApp.map

# Release a dev Android build to just 1/4 of your end users
code-push release-react MyApp-Android android --rollout 25% --dev true

# Release an update that targets users running any 1.1.* binary, as opposed to
# limiting the update to exact version name in the build.gradle file
code-push release-react MyApp-Android android --targetBinaryVersion "~1.1.0"

The CodePush client supports differential updates, so even though you are releasing your JS bundle and assets on every update, your end users will only actually download the files they need. The service handles this automatically so that you can focus on creating awesome apps and we can worry about optimizing end user downloads.

For more details about how the release-react command works, as well as the various parameters it exposes, refer to the CLI docs. Additionally, if you would prefer to handle running the react-native bundle command yourself, and therefore, want an even more flexible solution than release-react, refer to the release command for more details.

If you run into any issues, or have any questions/comments/feedback, you can ping us within the #code-push channel on Reactiflux, e-mail us and/or check out the troubleshooting details below.

NOTE: CodePush updates should be tested in modes other than Debug mode. In Debug mode, React Native app always downloads JS bundle generated by packager, so JS bundle downloaded by CodePush does not apply. You can see your update with more information at AppCenter: https://appcenter.ms/apps, choose your application -> Distribute -> CodePush. If you want disable an update, you can disbale it on AppCenter: choose your application -> Distribute -> CodePush -> Choose your version -> Choose Setting icon on the top of page then switch enable to disable.

API Reference

The CodePush plugin is made up of two components:

  1. A JavaScript module, which can be imported/required, and allows the app to interact with the service during runtime (e.g. check for updates, inspect the metadata about the currently running app update).

  2. A native API (Objective-C and Java) which allows the React Native app host to bootstrap itself with the right JS bundle location.

The following sections describe the shape and behavior of these APIs in detail:

JavaScript API Reference

When you require react-native-code-push, the module object provides the following top-level methods in addition to the root-level component decorator:

  • allowRestart: Re-allows programmatic restarts to occur as a result of an update being installed, and optionally, immediately restarts the app if a pending update had attempted to restart the app while restarts were disallowed. This is an advanced API and is only necessary if your app explicitly disallowed restarts via the disallowRestart method.

  • checkForUpdate: Asks the CodePush service whether the configured app deployment has an update available.

  • disallowRestart: Temporarily disallows any programmatic restarts to occur as a result of a CodePush update being installed. This is an advanced API, and is useful when a component within your app (e.g. an onboarding process) needs to ensure that no end-user interruptions can occur during its lifetime.

  • getCurrentPackage: Retrieves the metadata about the currently installed update (e.g. description, installation time, size). NOTE: As of v1.10.3-beta of the CodePush module, this method is deprecated in favor of getUpdateMetadata.

  • getUpdateMetadata: Retrieves the metadata for an installed update (e.g. description, mandatory).

  • notifyAppReady: Notifies the CodePush runtime that an installed update is considered successful. If you are manually checking for and installing updates (i.e. not using the sync method to handle it all for you), then this method MUST be called; otherwise CodePush will treat the update as failed and rollback to the previous version when the app next restarts.

  • restartApp: Immediately restarts the app. If there is an update pending, it will be immediately displayed to the end user. Otherwise, calling this method simply has the same behavior as the end user killing and restarting the process.

  • sync: Allows checking for an update, downloading it and installing it, all with a single call. Unless you need custom UI and/or behavior, we recommend most developers to use this method when integrating CodePush into their apps

  • clearUpdates: Clear all downloaded CodePush updates. This is useful when switching to a different deployment which may have an older release than the current package.

    Note: we don’t recommend to use this method in scenarios other than that (CodePush will call this method automatically when needed in other cases) as it could lead to unpredictable behavior.

codePush

// Wrapper function
codePush(rootComponent: React.Component): React.Component;
codePush(options: CodePushOptions)(rootComponent: React.Component): React.Component;
// Decorator; Requires ES7 support
@codePush
@codePush(options: CodePushOptions)

Used to wrap a React component inside a "higher order" React component that knows how to synchronize your app's JavaScript bundle and image assets when it is mounted. Internally, the higher-order component calls sync inside its componentDidMount lifecycle handle, which in turns performs an update check, downloads the update if it exists and installs the update for you.

This decorator provides support for letting you customize its behaviour to easily enable apps with different requirements. Below are some examples of ways you can use it (you can pick one or even use a combination):

  1. Silent sync on app start (the simplest, default behavior). Your app will automatically download available updates, and apply them the next time the app restarts (e.g. the OS or end user killed it, or the device was restarted). This way, the entire update experience is "silent" to the end user, since they don't see any update prompt and/or "synthetic" app restarts.

    // Fully silent update which keeps the app in
    // sync with the server, without ever
    // interrupting the end user
    class MyApp extends Component<{}> {}
    MyApp = codePush(MyApp);
    export default MyApp;
  2. Silent sync everytime the app resumes. Same as 1, except we check for updates, or apply an update if one exists every time the app returns to the foreground after being "backgrounded".

    // Sync for updates everytime the app resumes.
    class MyApp extends Component<{}> {}
    MyApp = codePush({ checkFrequency: codePush.CheckFrequency.ON_APP_RESUME, installMode: codePush.InstallMode.ON_NEXT_RESUME })(MyApp);
    export default MyApp;
  3. Interactive. When an update is available, prompt the end user for permission before downloading it, and then immediately apply the update. If an update was released using the mandatory flag, the end user would still be notified about the update, but they wouldn't have the choice to ignore it.

    // Active update, which lets the end user know
    // about each update, and displays it to them
    // immediately after downloading it
    class MyApp extends Component<{}> {}
    MyApp = codePush({ updateDialog: true, installMode: codePush.InstallMode.IMMEDIATE })(MyApp);
    export default MyApp;
  4. Log/display progress. While the app is syncing with the server for updates, make use of the codePushStatusDidChange and/or codePushDownloadDidProgress event hooks to log down the different stages of this process, or even display a progress bar to the user.

    // Make use of the event hooks to keep track of
    // the different stages of the sync process.
    class MyApp extends Component<{}> {
        codePushStatusDidChange(status) {
            switch(status) {
                case codePush.SyncStatus.CHECKING_FOR_UPDATE:
                    console.log("Checking for updates.");
                    break;
                case codePush.SyncStatus.DOWNLOADING_PACKAGE:
                    console.log("Downloading package.");
                    break;
                case codePush.SyncStatus.INSTALLING_UPDATE:
                    console.log("Installing update.");
                    break;
                case codePush.SyncStatus.UP_TO_DATE:
                    console.log("Up-to-date.");
                    break;
                case codePush.SyncStatus.UPDATE_INSTALLED:
                    console.log("Update installed.");
                    break;
            }
        }
    
        codePushDownloadDidProgress(progress) {
            console.log(progress.receivedBytes + " of " + progress.totalBytes + " received.");
        }
    }
    MyApp = codePush(MyApp);
    export default MyApp;
CodePushOptions

The codePush decorator accepts an "options" object that allows you to customize numerous aspects of the default behavior mentioned above:

  • checkFrequency (codePush.CheckFrequency) - Specifies when you would like to check for updates. Defaults to codePush.CheckFrequency.ON_APP_START. Refer to the CheckFrequency enum reference for a description of the available options and what they do.

  • deploymentKey (String) - Specifies the deployment key you want to query for an update against. By default, this value is derived from the Info.plist file (iOS) and MainActivity.java file (Android), but this option allows you to override it from the script-side if you need to dynamically use a different deployment.

  • installMode (codePush.InstallMode) - Specifies when you would like to install optional updates (i.e. those that aren't marked as mandatory). Defaults to codePush.InstallMode.ON_NEXT_RESTART. Refer to the InstallMode enum reference for a description of the available options and what they do.

  • mandatoryInstallMode (codePush.InstallMode) - Specifies when you would like to install updates which are marked as mandatory. Defaults to codePush.InstallMode.IMMEDIATE. Refer to the InstallMode enum reference for a description of the available options and what they do.

  • minimumBackgroundDuration (Number) - Specifies the minimum number of seconds that the app needs to have been in the background before restarting the app. This property only applies to updates which are installed using InstallMode.ON_NEXT_RESUME or InstallMode.ON_NEXT_SUSPEND, and can be useful for getting your update in front of end users sooner, without being too obtrusive. Defaults to 0, which has the effect of applying the update immediately after a resume or unless the app suspension is long enough to not matter, regardless how long it was in the background.

  • updateDialog (UpdateDialogOptions) - An "options" object used to determine whether a confirmation dialog should be displayed to the end user when an update is available, and if so, what strings to use. Defaults to null, which has the effect of disabling the dialog completely. Setting this to any truthy value will enable the dialog with the default strings, and passing an object to this parameter allows enabling the dialog as well as overriding one or more of the default strings. Before enabling this option within an App Store-distributed app, please refer to this note.

    The following list represents the available options and their defaults:

    • appendReleaseDescription (Boolean) - Indicates whether you would like to append the description of an available release to the notification message which is displayed to the end user. Defaults to false.

    • descriptionPrefix (String) - Indicates the string you would like to prefix the release description with, if any, when displaying the update notification to the end user. Defaults to " Description: "

    • mandatoryContinueButtonLabel (String) - The text to use for the button the end user must press in order to install a mandatory update. Defaults to "Continue".

    • mandatoryUpdateMessage (String) - The text used as the body of an update notification, when the update is specified as mandatory. Defaults to "An update is available that must be installed.".

    • optionalIgnoreButtonLabel (String) - The text to use for the button the end user can press in order to ignore an optional update that is available. Defaults to "Ignore".

    • optionalInstallButtonLabel (String) - The text to use for the button the end user can press in order to install an optional update. Defaults to "Install".

    • optionalUpdateMessage (String) - The text used as the body of an update notification, when the update is optional. Defaults to "An update is available. Would you like to install it?".

    • title (String) - The text used as the header of an update notification that is displayed to the end user. Defaults to "Update available".

codePushStatusDidChange (event hook)

Called when the sync process moves from one stage to another in the overall update process. The event hook is called with a status code which represents the current state, and can be any of the SyncStatus values.

codePushDownloadDidProgress (event hook)

Called periodically when an available update is being downloaded from the CodePush server. The method is called with a DownloadProgress object, which contains the following two properties:

  • totalBytes (Number) - The total number of bytes expected to be received for this update (i.e. the size of the set of files which changed from the previous release).

  • receivedBytes (Number) - The number of bytes downloaded thus far, which can be used to track download progress.

codePush.allowRestart

codePush.allowRestart(): void;

Re-allows programmatic restarts to occur, that would have otherwise been rejected due to a previous call to disallowRestart. If disallowRestart was never called in the first place, then calling this method will simply result in a no-op.

If a CodePush update is currently pending, which attempted to restart the app (e.g. it used InstallMode.IMMEDIATE), but was blocked due to disallowRestart having been called, then calling allowRestart will result in an immediate restart. This allows the update to be applied as soon as possible, without interrupting the end user during critical workflows (e.g. an onboarding process).

For example, calling allowRestart would trigger an immediate restart if either of the three scenarios mentioned in the disallowRestart docs occured after disallowRestart was called. However, calling allowRestart wouldn't trigger a restart if the following were true:

  1. No CodePush updates were installed since the last time disallowRestart was called, and therefore, there isn't any need to restart anyways.

  2. There is currently a pending CodePush update, but it was installed via InstallMode.ON_NEXT_RESTART, and therefore, doesn't require a programmatic restart.

  3. There is currently a pending CodePush update, but it was installed via InstallMode.ON_NEXT_RESUME and the app hasn't been put into the background yet, and therefore, there isn't a need to programmatically restart yet.

  4. No calls to restartApp were made since the last time disallowRestart was called.

This behavior ensures that no restarts will be triggered as a result of calling allowRestart unless one was explictly requested during the disallowed period. In this way, allowRestart is somewhat similar to calling restartApp(true), except the former will only trigger a restart if the currently pending update wanted to restart, whereas the later would restart as long as an update is pending.

See disallowRestart for an example of how this method can be used.

codePush.checkForUpdate

codePush.checkForUpdate(deploymentKey: String = null, handleBinaryVersionMismatchCallback: (update: RemotePackage) => void): Promise<RemotePackage>;

Queries the CodePush service to see whether the configured app deployment has an update available. By default, it will use the deployment key that is configured in your Info.plist file (iOS), or MainActivity.java file (Android), but you can override that by specifying a value via the optional deploymentKey parameter. This can be useful when you want to dynamically "redirect" a user to a specific deployment, such as allowing "early access" via an easter egg or a user setting switch.

Second optional parameter handleBinaryVersionMismatchCallback is an optional callback function that can be used to notify user if there are any binary update. E.g. consider a use-case where currently installed binary version is 1.0.1 with label(codepush label) v1. Later native code was changed in the dev cycle and binary version was updated to 1.0.2. When code-push update check is triggered we ignore updates having binary version mismatch (because the update is not targeting to the binary version of currently installed app). In this case installed app (1.0.1) will ignore the update targeting version 1.0.2. You can use handleBinaryVersionMismatchCallback to provide a hook to handle such situations.

NOTE: Be cautious to use Alerts within this callback if you are developing iOS application, due to App Store review process:

Apps must not force users to rate the app, review the app, download other apps, or other similar actions in order to access functionality, content, or use of the app.

This method returns a Promise which resolves to one of two possible values:

  1. null if there is no update available. This can occur in the following scenarios:

    1. The configured deployment doesn't contain any releases, and therefore, nothing to update.
    2. The latest release within the configured deployment is targeting a different binary version than what you're currently running (either older or newer).
    3. The currently running app already has the latest release from the configured deployment, and therefore, doesn't need it again.
    4. The latest release within the configured deployment is currently marked as disabled, and therefore, isn't allowed to be downloaded.
    5. The latest release within the configured deployment is in an "active rollout" state, and the requesting device doesn't fall within the percentage of users who are eligible for it.
  2. A RemotePackage instance which represents an available update that can be inspected and/or subsequently downloaded.

Example Usage:

codePush.checkForUpdate()
.then((update) => {
    if (!update) {
        console.log("The app is up to date!");
    } else {
        console.log("An update is available! Should we download it?");
    }
});

codePush.disallowRestart

codePush.disallowRestart(): void;

Temporarily disallows programmatic restarts to occur as a result of either of following scenarios:

  1. A CodePush update is installed using InstallMode.IMMEDIATE
  2. A CodePush update is installed using InstallMode.ON_NEXT_RESUME and the app is resumed from the background (optionally being throttled by the minimumBackgroundDuration property)
  3. The restartApp method was called

NOTE: #1 and #2 effectively work by calling restartApp for you, so you can think of disallowRestart as blocking any call to restartApp, regardless if your app calls it directly or indirectly.

After calling this method, any calls to sync would still be allowed to check for an update, download it and install it, but an attempt to restart the app would be queued until allowRestart is called. This way, the restart request is captured and can be "flushed" whenever you want to allow it to occur.

This is an advanced API, and is primarily useful when individual components within your app (e.g. an onboarding process) need to ensure that no end-user interruptions can occur during their lifetime, while continuing to allow the app to keep syncing with the CodePush server at its own pace and using whatever install modes are appropriate. This has the benefit of allowing the app to discover and download available updates as soon as possible, while also preventing any disruptions during key end-user experiences.

As an alternative, you could also choose to simply use InstallMode.ON_NEXT_RESTART whenever calling sync (which will never attempt to programmatically restart the app), and then explicity calling restartApp at points in your app that you know it is "safe" to do so. disallowRestart provides an alternative approach to this when the code that synchronizes with the CodePush server is separate from the code/components that want to enforce a no-restart policy.

Example Usage:

class OnboardingProcess extends Component {
    ...

    componentWillMount() {
        // Ensure that any CodePush updates which are
        // synchronized in the background can't trigger
        // a restart while this component is mounted.
        codePush.disallowRestart();
    }

    componentWillUnmount() {
        // Reallow restarts, and optionally trigger
        // a restart if one was currently pending.
        codePush.allowRestart();
    }

    ...
}

codePush.getCurrentPackage

NOTE: This method is considered deprecated as of v1.10.3-beta of the CodePush module. If you're running this version (or newer), we would recommend using the codePush.getUpdateMetadata instead, since it has more predictable behavior.

codePush.getCurrentPackage(): Promise<LocalPackage>;

Retrieves the metadata about the currently installed "package" (e.g. description, installation time). This can be useful for scenarios such as displaying a "what's new?" dialog after an update has been applied or checking whether there is a pending update that is waiting to be applied via a resume or restart.

This method returns a Promise which resolves to one of two possible values:

  1. null if the app is currently running the JS bundle from the binary and not a CodePush update. This occurs in the following scenarios:

    1. The end-user installed the app binary and has yet to install a CodePush update
    2. The end-user installed an update of the binary (e.g. from the store), which cleared away the old CodePush updates, and gave precedence back to the JS binary in the binary.
  2. A LocalPackage instance which represents the metadata for the currently running CodePush update.

Example Usage:

codePush.getCurrentPackage()
.then((update) => {
    // If the current app "session" represents the first time
    // this update has run, and it had a description provided
    // with it upon release, let's show it to the end user
    if (update.isFirstRun && update.description) {
        // Display a "what's new?" modal
    }
});

codePush.getUpdateMetadata

codePush.getUpdateMetadata(updateState: UpdateState = UpdateState.RUNNING): Promise<LocalPackage>;

Retrieves the metadata for an installed update (e.g. description, mandatory) whose state matches the specified updateState parameter. This can be useful for scenarios such as displaying a "what's new?" dialog after an update has been applied or checking whether there is a pending update that is waiting to be applied via a resume or restart. For more details about the possible update states, and what they represent, refer to the UpdateState reference.

This method returns a Promise which resolves to one of two possible values:

  1. null if an update with the specified state doesn't currently exist. This occurs in the following scenarios:

    1. The end-user hasn't installed any CodePush updates yet, and therefore, no metadata is available for any updates, regardless what you specify as the updateState parameter.

    2. The end-user installed an update of the binary (e.g. from the store), which cleared away the old CodePush updates, and gave precedence back to the JS binary in the binary. Therefore, it would exhibit the same behavior as #1

    3. The updateState parameter is set to UpdateState.RUNNING, but the app isn't currently running a CodePush update. There may be a pending update, but the app hasn't been restarted yet in order to make it active.

    4. The updateState parameter is set to UpdateState.PENDING, but the app doesn't have any currently pending updates.

  2. A LocalPackage instance which represents the metadata for the currently requested CodePush update (either the running or pending).

Example Usage:

// Check if there is currently a CodePush update running, and if
// so, register it with the HockeyApp SDK (https://github.com/slowpath/react-native-hockeyapp)
// so that crash reports will correctly display the JS bundle version the user was running.
codePush.getUpdateMetadata().then((update) => {
    if (update) {
        hockeyApp.addMetadata({ CodePushRelease: update.label });
    }
});

// Check to see if there is still an update pending.
codePush.getUpdateMetadata(UpdateState.PENDING).then((update) => {
    if (update) {
        // There's a pending update, do we want to force a restart?
    }
});

codePush.notifyAppReady

codePush.notifyAppReady(): Promise<void>;

Notifies the CodePush runtime that a freshly installed update should be considered successful, and therefore, an automatic client-side rollback isn't necessary. It is mandatory to call this function somewhere in the code of the updated bundle. Otherwise, when the app next restarts, the CodePush runtime will assume that the installed update has failed and roll back to the previous version. This behavior exists to help ensure that your end users aren't blocked by a broken update.

If you are using the sync function, and doing your update check on app start, then you don't need to manually call notifyAppReady since sync will call it for you. This behavior exists due to the assumption that the point at which sync is called in your app represents a good approximation of a successful startup.

NOTE: This method is also aliased as notifyApplicationReady (for backwards compatibility).

codePush.restartApp

codePush.restartApp(onlyIfUpdateIsPending: Boolean = false): void;

Immediately restarts the app. If a truthy value is provided to the onlyIfUpdateIsPending parameter, then the app will only restart if there is actually a pending update waiting to be applied.

This method is for advanced scenarios, and is primarily useful when the following conditions are true:

  1. Your app is specifying an install mode value of ON_NEXT_RESTART or ON_NEXT_RESUME when calling the sync or LocalPackage.install methods. This has the effect of not applying your update until the app has been restarted (by either the end user or OS) or resumed, and therefore, the update won't be immediately displayed to the end user.

  2. You have an app-specific user event (e.g. the end user navigated back to the app's home route) that allows you to apply the update in an unobtrusive way, and potentially gets the update in front of the end user sooner then waiting until the next restart or resume.

codePush.sync

codePush.sync(options: Object, syncStatusChangeCallback: function(syncStatus: Number), downloadProgressCallback: function(progress: DownloadProgress), handleBinaryVersionMismatchCallback: function(update: RemotePackage)): Promise<Number>;

Synchronizes your app's JavaScript bundle and image assets with the latest release to the configured deployment. Unlike the checkForUpdate method, which simply checks for the presence of an update, and let's you control what to do next, sync handles the update check, download and installation experience for you.

This method provides support for two different (but customizable) "modes" to easily enable apps with different requirements:

  1. Silent mode (the default behavior), which automatically downloads available updates, and applies them the next time the app restarts (e.g. the OS or end user killed it, or the device was restarted). This way, the entire update experience is "silent" to the end user, since they don't see any update prompt and/or "synthetic" app restarts.

  2. Active mode, which when an update is available, prompts the end user for permission before downloading it, and then immediately applies the update. If an update was released using the mandatory flag, the end user would still be notified about the update, but they wouldn't have the choice to ignore it.

Example Usage:

// Fully silent update which keeps the app in
// sync with the server, without ever
// interrupting the end user
codePush.sync();

// Active update, which lets the end user know
// about each update, and displays it to them
// immediately after downloading it
codePush.sync({ updateDialog: true, installMode: codePush.InstallMode.IMMEDIATE });

Note: If you want to decide whether you check and/or download an available update based on the end user's device battery level, network conditions, etc. then simply wrap the call to sync in a condition that ensures you only call it when desired.

SyncOptions

While the sync method tries to make it easy to perform silent and active updates with little configuration, it accepts an "options" object that allows you to customize numerous aspects of the default behavior mentioned above. The options available are identical to the CodePushOptions, with the exception of the checkFrequency option:

Example Usage:

// Use a different deployment key for this
// specific call, instead of the one configured
// in the Info.plist file
codePush.sync({ deploymentKey: "KEY" });

// Download the update silently, but install it on
// the next resume, as long as at least 5 minutes
// has passed since the app was put into the background.
codePush.sync({ installMode: codePush.InstallMode.ON_NEXT_RESUME, minimumBackgroundDuration: 60 * 5 });

// Download the update silently, and install optional updates
// on the next restart, but install mandatory updates on the next resume.
codePush.sync({ mandatoryInstallMode: codePush.InstallMode.ON_NEXT_RESUME });

// Changing the title displayed in the
// confirmation dialog of an "active" update
codePush.sync({ updateDialog: { title: "An update is available!" } });

// Displaying an update prompt which includes the
// description associated with the CodePush release
codePush.sync({
   updateDialog: {
    appendReleaseDescription: true,
    descriptionPrefix: "\n\nChange log:\n"
   },
   installMode: codePush.InstallMode.IMMEDIATE
});

In addition to the options, the sync method also accepts several optional function parameters which allow you to subscribe to the lifecycle of the sync "pipeline" in order to display additional UI as needed (e.g. a "checking for update modal or a download progress modal):

  • syncStatusChangedCallback ((syncStatus: Number) => void) - Called when the sync process moves from one stage to another in the overall update process. The method is called with a status code which represents the current state, and can be any of the SyncStatus values.

  • downloadProgressCallback ((progress: DownloadProgress) => void) - Called periodically when an available update is being downloaded from the CodePush server. The method is called with a DownloadProgress object, which contains the following two properties:

    • totalBytes (Number) - The total number of bytes expected to be received for this update (i.e. the size of the set of files which changed from the previous release).

    • receivedBytes (Number) - The number of bytes downloaded thus far, which can be used to track download progress.

  • handleBinaryVersionMismatchCallback ((update: RemotePackage) => void) - Called when there are any binary update available. The method is called with a RemotePackage object. Refer to codePush.checkForUpdate section for more details.

Example Usage:

// Prompt the user when an update is available
// and then display a "downloading" modal
codePush.sync({ updateDialog: true },
  (status) => {
      switch (status) {
          case codePush.SyncStatus.DOWNLOADING_PACKAGE:
              // Show "downloading" modal
              break;
          case codePush.SyncStatus.INSTALLING_UPDATE:
              // Hide "downloading" modal
              break;
      }
  },
  ({ receivedBytes, totalBytes, }) => {
    /* Update download modal progress */
  }
);

This method returns a Promise which is resolved to a SyncStatus code that indicates why the sync call succeeded. This code can be one of the following SyncStatus values:

  • codePush.SyncStatus.UP_TO_DATE (0) - The app is up-to-date with the CodePush server.

  • codePush.SyncStatus.UPDATE_IGNORED (2) - The app had an optional update which the end user chose to ignore. (This is only applicable when the updateDialog is used)

  • codePush.SyncStatus.UPDATE_INSTALLED (1) - The update has been installed and will be run either immediately after the syncStatusChangedCallback function returns or the next time the app resumes/restarts, depending on the InstallMode specified in SyncOptions.

  • codePush.SyncStatus.SYNC_IN_PROGRESS (4) - There is an ongoing sync operation running which prevents the current call from being executed.

The sync method can be called anywhere you'd like to check for an update. That could be in the componentWillMount lifecycle event of your root component, the onPress handler of a <TouchableHighlight> component, in the callback of a periodic timer, or whatever else makes sense for your needs. Just like the checkForUpdate method, it will perform the network request to check for an update in the background, so it won't impact your UI thread and/or JavaScript thread's responsiveness.

Package objects

The checkForUpdate and getUpdateMetadata methods return Promise objects, that when resolved, provide acces to "package" objects. The package represents your code update as well as any extra metadata (e.g. description, mandatory?). The CodePush API has the distinction between the following types of packages:

  • LocalPackage: Represents a downloaded update that is either already running, or has been installed and is pending an app restart.

  • RemotePackage: Represents an available update on the CodePush server that hasn't been downloaded yet.

LocalPackage

Contains details about an update that has been downloaded locally or already installed. You can get a reference to an instance of this object either by calling the module-level getUpdateMetadata method, or as the value of the promise returned by the RemotePackage.download method.

Properties
  • appVersion: The app binary version that this update is dependent on. This is the value that was specified via the appStoreVersion parameter when calling the CLI's release command. (String)
  • deploymentKey: The deployment key that was used to originally download this update. (String)
  • description: The description of the update. This is the same value that you specified in the CLI when you released the update. (String)
  • failedInstall: Indicates whether this update has been previously installed but was rolled back. The sync method will automatically ignore updates which have previously failed, so you only need to worry about this property if using checkForUpdate. (Boolean)
  • isFirstRun: Indicates whether this is the first time the update has been run after being installed. This is useful for determining whether you would like to show a "What's New?" UI to the end user after installing an update. (Boolean)
  • isMandatory: Indicates whether the update is considered mandatory. This is the value that was specified in the CLI when the update was released. (Boolean)
  • isPending: Indicates whether this update is in a "pending" state. When true, that means the update has been downloaded and installed, but the app restart needed to apply it hasn't occurred yet, and therefore, it's changes aren't currently visible to the end-user. (Boolean)
  • label: The internal label automatically given to the update by the CodePush server, such as v5. This value uniquely identifies the update within it's deployment. (String)
  • packageHash: The SHA hash value of the update. (String)
  • packageSize: The size of the code contained within the update, in bytes. (Number)
Methods
  • install(installMode: codePush.InstallMode = codePush.InstallMode.ON_NEXT_RESTART, minimumBackgroundDuration = 0): Promise<void>: Installs the update by saving it to the location on disk where the runtime expects to find the latest version of the app. The installMode parameter controls when the changes are actually presented to the end user. The default value is to wait until the next app restart to display the changes, but you can refer to the InstallMode enum reference for a description of the available options and what they do. If the installMode parameter is set to InstallMode.ON_NEXT_RESUME, then the minimumBackgroundDuration parameter allows you to control how long the app must have been in the background before forcing the install after it is resumed.
RemotePackage

Contains details about an update that is available for download from the CodePush server. You get a reference to an instance of this object by calling the checkForUpdate method when an update is available. If you are using the sync API, you don't need to worry about the RemotePackage, since it will handle the download and installation process automatically for you.

Properties

The RemotePackage inherits all of the same properties as the LocalPackage, but includes one additional one:

  • downloadUrl: The URL at which the package is available for download. This property is only needed for advanced usage, since the download method will automatically handle the acquisition of updates for you. (String)
Methods
  • download(downloadProgressCallback?: Function): Promise<LocalPackage>: Downloads the available update from the CodePush service. If a downloadProgressCallback is specified, it will be called periodically with a DownloadProgress object ({ totalBytes: Number, receivedBytes: Number }) that reports the progress of the download until it completes. Returns a Promise that resolves with the LocalPackage.

Enums

The CodePush API includes the following enums which can be used to customize the update experience:

InstallMode

This enum specifies when you would like an installed update to actually be applied, and can be passed to either the sync or LocalPackage.install methods. It includes the following values:

  • codePush.InstallMode.IMMEDIATE (0) - Indicates that you want to install the update and restart the app immediately. This value is appropriate for debugging scenarios as well as when displaying an update prompt to the user, since they would expect to see the changes immediately after accepting the installation. Additionally, this mode can be used to enforce mandatory updates, since it removes the potentially undesired latency between the update installation and the next time the end user restarts or resumes the app.

  • codePush.InstallMode.ON_NEXT_RESTART (1) - Indicates that you want to install the update, but not forcibly restart the app. When the app is "naturally" restarted (due the OS or end user killing it), the update will be seamlessly picked up. This value is appropriate when performing silent updates, since it would likely be disruptive to the end user if the app suddenly restarted out of nowhere, since they wouldn't have realized an update was even downloaded. This is the default mode used for both the sync and LocalPackage.install methods.

  • codePush.InstallMode.ON_NEXT_RESUME (2) - Indicates that you want to install the update, but don't want to restart the app until the next time the end user resumes it from the background. This way, you don't disrupt their current session, but you can get the update in front of them sooner then having to wait for the next natural restart. This value is appropriate for silent installs that can be applied on resume in a non-invasive way.

  • codePush.InstallMode.ON_NEXT_SUSPEND (3) - Indicates that you want to install the update while it is in the background, but only after it has been in the background for minimumBackgroundDuration seconds (0 by default), so that user context isn't lost unless the app suspension is long enough to not matter.

CheckFrequency

This enum specifies when you would like your app to sync with the server for updates, and can be passed to the codePushify decorator. It includes the following values:

  • codePush.CheckFrequency.ON_APP_START (0) - Indicates that you want to check for updates whenever the app's process is started.

  • codePush.CheckFrequency.ON_APP_RESUME (1) - Indicates that you want to check for updates whenever the app is brought back to the foreground after being "backgrounded" (user pressed the home button, app launches a seperate payment process, etc).

  • codePush.CheckFrequency.MANUAL (2) - Disable automatic checking for updates, but only check when codePush.sync() is called in app code.

SyncStatus

This enum is provided to the syncStatusChangedCallback function that can be passed to the sync method, in order to hook into the overall update process. It includes the following values:

  • codePush.SyncStatus.UP_TO_DATE (0) - The app is fully up-to-date with the configured deployment.
  • codePush.SyncStatus.UPDATE_INSTALLED (1) - An available update has been installed and will be run either immediately after the syncStatusChangedCallback function returns or the next time the app resumes/restarts, depending on the InstallMode specified in SyncOptions.
  • codePush.SyncStatus.UPDATE_IGNORED (2) - The app has an optional update, which the end user chose to ignore. (This is only applicable when the updateDialog is used)
  • codePush.SyncStatus.UNKNOWN_ERROR (3) - The sync operation encountered an unknown error.
  • codePush.SyncStatus.SYNC_IN_PROGRESS (4) - There is an ongoing sync operation running which prevents the current call from being executed.
  • codePush.SyncStatus.CHECKING_FOR_UPDATE (5) - The CodePush server is being queried for an update.
  • codePush.SyncStatus.AWAITING_USER_ACTION (6) - An update is available, and a confirmation dialog was shown to the end user. (This is only applicable when the updateDialog is used)
  • codePush.SyncStatus.DOWNLOADING_PACKAGE (7) - An available update is being downloaded from the CodePush server.
  • codePush.SyncStatus.INSTALLING_UPDATE (8) - An available update was downloaded and is about to be installed.
UpdateState

This enum specifies the state that an update is currently in, and can be specified when calling the getUpdateMetadata method. It includes the following values:

  • codePush.UpdateState.RUNNING (0) - Indicates that an update represents the version of the app that is currently running. This can be useful for identifying attributes about the app, for scenarios such as displaying the release description in a "what's new?" dialog or reporting the latest version to an analytics and/or crash reporting service.

  • codePush.UpdateState.PENDING (1) - Indicates than an update has been installed, but the app hasn't been restarted yet in order to apply it. This can be useful for determining whether there is a pending update, which you may want to force a programmatic restart (via restartApp) in order to apply.

  • codePush.UpdateState.LATEST (2) - Indicates than an update represents the latest available release, and can be either currently running or pending.

Store Guideline Compliance

While Google Play and internally distributed apps (e.g. Enterprise, Fabric, HockeyApp) have no limitations over how to publish updates using CodePush, the iOS App Store and its corresponding guidelines have more precise rules you should be aware of before integrating the solution within your application.

Paragraph 3.3.2, since back in 2015's Apple Developer Program License Agreement fully allowed performing over-the-air updates of JavaScript and assets - and in its latest version (20170605) downloadable here this ruling is even broader:

Interpreted code may be downloaded to an Application but only so long as such code: (a) does not change the primary purpose of the Application by providing features or functionality that are inconsistent with the intended and advertised purpose of the Application as submitted to the App Store, (b) does not create a store or storefront for other code or applications, and (c) does not bypass signing, sandbox, or other security features of the OS.

CodePush allows you to follow these rules in full compliance so long as the update you push does not significantly deviate your product from its original App Store approved intent.

To further remain in compliance with Apple's guidelines we suggest that App Store-distributed apps don't enable the updateDialog option when calling sync, since in the App Store Review Guidelines it is written that:

Apps must not force users to rate the app, review the app, download other apps, or other similar actions in order to access functionality, content, or use of the app.

This is not necessarily the case for updateDialog, since it won't force the user to download the new version, but at least you should be aware of that ruling if you decide to show it.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment