diff --git a/README.md b/README.md index 2103cb1d9..63158e35f 100644 --- a/README.md +++ b/README.md @@ -10,17 +10,17 @@ This plugin provides client-side integration for the [CodePush service](http://c * [Supported React Native Platforms](#supported-react-native-platforms) * [Supported Components](#supported-components) * [Getting Started](#getting-started) - * [iOS Setup](#ios-setup) - * [Android Setup](#android-setup) - * [Windows Setup](#windows-setup) + * [iOS Setup](docs/setup-ios.md) + * [Android Setup](docs/setup-android.md) + * [Windows Setup](docs/setup-windows.md) * [Plugin Usage](#plugin-usage) * [Releasing Updates](#releasing-updates) * [Multi-Deployment Testing](#multi-deployment-testing) * [Dynamic Deployment Assignment](#dynamic-deployment-assignment) * [API Reference](#api-reference) - * [JavaScript API](#javascript-api-reference) - * [Objective-C API Reference (iOS)](#objective-c-api-reference-ios) - * [Java API Reference (Android)](#java-api-reference-android) + * [JavaScript API](docs/api-js.md) + * [Objective-C API Reference (iOS)](docs/api-ios.md) + * [Java API Reference (Android)](docs/api-android.md) * [Debugging / Troubleshooting](#debugging--troubleshooting) * [Example Apps / Starters](#example-apps--starters) * [Continuous Integration / Delivery](#continuous-integration--delivery) @@ -77,6 +77,8 @@ The following list represents the set of components (and props) that don't curre As new core components are released, which support referencing assets, we'll update this list to ensure users know what exactly they can expect to update using CodePush. + + ## Getting Started Once you've followed the general-purpose ["getting started"](http://codepush.tools/docs/getting-started.html) 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: @@ -89,379 +91,12 @@ As with all other React Native plugins, the integration experience is different If you want to see how other projects have integrated with CodePush, you can check out the excellent [example apps](#example-apps--starters) 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](https://www.youtube.com/watch?v=uN0FRWk-YW8&feature=youtu.be) and/or [Deepak Sisodiya ](https://www.youtube.com/watch?v=f6I9y7V-Ibk). -## iOS Setup - -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**](#plugin-installation-ios---rnpm) - [React Native Package Manager (RNPM)](https://github.com/rnpm/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**](#plugin-installation-ios---cocoapods) - If you're building a native iOS app that is embedding React Native into it, or you simply prefer using [CocoaPods](https://cocoapods.org), then we recommend using the Podspec file that we ship as part of our plugin. - -3. [**"Manual"**](#plugin-installation-ios---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 -k`, or you can choose to ignore it (by simply hitting ``) 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 CodePush plugin dependency to your `Podfile`, pointing at the path where NPM installed it - - ```ruby - pod 'CodePush', :path => '../node_modules/react-native-code-push' - ``` - - CodePush depends on an internal copy of the `SSZipArchive` library, so if your project already includes it (either directly or via a transitive dependency), then you can install a version of CodePush which excludes it by depending specifically on the `Core` subspec: - - ```ruby - pod 'CodePush', :path => '../node_modules/react-native-code-push', :subspecs => ['Core'] - ``` - - *NOTE: The above paths needs to be relative to your app's `Podfile`, so adjust it as nec - cessary.* - -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](https://facebook.github.io/react-native/docs/integration-with-existing-apps.html#podfile).* - -#### 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](https://cloud.githubusercontent.com/assets/8598682/13368613/c5c21422-dca0-11e5-8594-c0ec5bde9d81.png) - -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](https://cloud.githubusercontent.com/assets/516559/10322221/a75ea066-6c31-11e5-9d88-ff6f6a4d6968.png) - -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](https://cloud.githubusercontent.com/assets/116461/11605042/6f786e64-9aaa-11e5-8ca7-14b852f808b1.png) - - *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: - - ```objective-c - #import - ``` - -2. Find the following line of code, which loads your JS Bundle from the app binary for production releases: - - ```objective-c - jsCodeLocation = [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"]; - ``` - -3. Replace it with this line: - - ```objective-c - 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. - -```objective-c -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 -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](https://cloud.githubusercontent.com/assets/116461/11601733/13011d5e-9a8a-11e5-9ce2-b100498ffb34.png) - -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](#multi-deployment-testing) docs below before actually moving your app's usage of CodePush into production. - -## Android Setup - -In order to integrate CodePush into your Android project, 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**](#plugin-installation-android---rnpm) - [React Native Package Manager (RNPM)](https://github.com/rnpm/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"**](#plugin-installation-android---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 -k`, or you can choose to ignore it (by simply hitting ``) 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](#plugin-configuration-android) section to complete the setup. - -#### Plugin Installation (Android - Manual) - -1. In your `android/settings.gradle` file, make the following additions: - - ```gradle - 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: - - ```gradle - ... - 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`: - - ```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** - -Update the `MainApplication.java` file to use CodePush via the following changes: - -```java -... -// 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 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 -k" to retrieve your key. - return Arrays.asList( - new MainReactPackage(), - new CodePush("deployment-key-here", MainApplication.this, BuildConfig.DEBUG) - ); - } - }; -} -``` - -**For React Native v0.19 - v0.28** - -Update the `MainActivity.java` file to use CodePush via the following changes: - -```java -... -// 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 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 -k" to retrieve your key. - return Arrays.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** - -Update the `MainApplication.java` file to use CodePush via the following changes: - -```java -... -// 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** - -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: - -```java -// 1. Provide your ReactInstanceHolder to CodePush. -public class MainApplication extends Application { +Then continue with installing the native module + * [iOS Setup](docs/setup-ios.md) + * [Android Setup](docs/setup-android.md) + * [Windows Setup](docs/setup-windows.md) - @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](#multi-deployment-testing) docs below before actually moving your app's usage of CodePush into production. - -## Windows Setup - -Once you've acquired the CodePush plugin, you need to integrate it into the Visual Studio project of your React Native app and configure it correctly. To do this, take the following steps: - -### Plugin Installation (Windows) - -1. Open the Visual Studio solution located at `windows\\.sln` within your app - -2. Right-click the solution node in the `Solution Explorer` window and select the `Add -> Existing Project...` menu item - - ![Add Project](https://cloud.githubusercontent.com/assets/116461/14467164/ddf6312e-008e-11e6-8a10-44a8b44b5dfc.PNG) - -3. Browse to the `node_modules\react-native-code-push\windows` directory, select the `CodePush.csproj` file and click `OK` - -4. Back in the `Solution Explorer`, right-click the project node that is named after your app, and select the `Add -> Reference...` menu item - - ![Add Reference](https://cloud.githubusercontent.com/assets/116461/14467154/d833bc98-008e-11e6-8e95-09864b1f05ef.PNG) - -5. Select the `Projects` tab on the left hand side, check the `CodePush` item and then click `OK` - - ![Add Reference Dialog](https://cloud.githubusercontent.com/assets/116461/14467147/cb805b6e-008e-11e6-964f-f856c59b65af.PNG) - -### Plugin Configuration (Windows) - -After installing the plugin, 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, update the `AppReactPage.cs` file to use CodePush via the following changes: - -```c# -... -// 1. Import the CodePush namespace -using CodePush.ReactNative; -... -class AppReactPage : ReactPage -{ - // 2. Declare a private instance variable for the CodePushModule instance. - private CodePushReactPackage codePushReactPackage; - - // 3. Update the JavaScriptBundleFile property to initalize the CodePush runtime, - // specifying the right deployment key, then use it to return the bundle URL from - // CodePush instead of statically from the binary. If you don't already have your - // deployment key, you can run "code-push deployment ls -k" to retrieve it. - public override string JavaScriptBundleFile - { - get - { - codePushReactPackage = new CodePushReactPackage("deployment-key-here", this); - return codePushReactPackage.GetJavaScriptBundleFile(); - } - } - - // 4. Add the codePushReactPackage instance to the list of existing packages. - public override List Packages - { - get - { - return new List - { - new MainReactPackage(), - ... - codePushReactPackage - }; - } - } - ... -} -``` ## Plugin Usage @@ -509,7 +144,7 @@ class MyApp extends Component { MyApp = codePush(codePushOptions)(MyApp); ``` -Alternatively, if you want fine-grained control over when the check happens (e.g. a button press or timer interval), you can call [`CodePush.sync()`](#codepushsync) at any time with your desired `SyncOptions`, and optionally turn off CodePush's automatic checking by specifying a manual `checkFrequency`: +Alternatively, if you want fine-grained control over when the check happens (e.g. a button press or timer interval), you can call [`CodePush.sync()`](docs/api-js#codepushsync) at any time with your desired `SyncOptions`, and optionally turn off CodePush's automatic checking by specifying a manual `checkFrequency`: ```javascript let codePushOptions = { checkFrequency: codePush.CheckFrequency.MANUAL }; @@ -534,7 +169,7 @@ class MyApp extends Component { MyApp = codePush(codePushOptions)(MyApp); ``` -If you would like to display an update confirmation dialog (an "active install"), configure when an available update is installed (e.g. force an immediate restart) or customize the update experience in any other way, refer to the [`codePush()`](#codepush) API reference for information on how to tweak this default behavior. +If you would like to display an update confirmation dialog (an "active install"), configure when an available update is installed (e.g. force an immediate restart) or customize the update experience in any other way, refer to the [`codePush()`](docs/api-js#codepush) API reference for information on how to tweak this default behavior. *NOTE: If you are using [Redux](http://redux.js.org) and [Redux Saga](http://yelouafi.github.io/redux-saga/), you can alternatively use the [react-native-code-push-saga](http://github.com/lostintangent/react-native-code-push-saga) module, which allows you to customize when `sync` is called in a perhaps simpler/more idiomatic way.* @@ -763,630 +398,6 @@ 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.* --- - -## 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](#codepush): - -* [allowRestart](#codepushallowrestart): 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](#codepushcheckforupdate): Asks the CodePush service whether the configured app deployment has an update available. - -* [disallowRestart](#codepushdisallowrestart): 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](#codepushgetcurrentpackage): 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`](#codepushgetupdatemetadata)*. - -* [getUpdateMetadata](#codepushgetupdatemetadata): Retrieves the metadata for an installed update (e.g. description, mandatory). - -* [notifyAppReady](#codepushnotifyappready): 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](#codepushsync) 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](#codepushrestartapp): 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](#codepushsync): 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 - -#### codePush - -```javascript -// Wrapper function -codePush(rootComponent: React.Component): React.Component; -codePush(options: CodePushOptions)(rootComponent: React.Component): React.Component; -``` -```javascript -// 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`](#codepushsync) 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. - - ```javascript - // 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); - ``` - -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". - - ```javascript - // 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); - ``` - -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. - - ```javascript - // 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); - ``` - -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. - - ```javascript - // 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); - ``` - -##### 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`](#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`](#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`](#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`, 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, 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](#user-content-apple-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`](#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 - -```javascript -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](#codepushdisallowrestart) 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](#codepushdisallowrestart) for an example of how this method can be used. - -#### codePush.checkForUpdate - -```javascript -codePush.checkForUpdate(deploymentKey: String = null): Promise; -``` - -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. - -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`](#remotepackage) instance which represents an available update that can be inspected and/or subsequently downloaded. - -Example Usage: - -```javascript -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 - -```javascript -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: - -```javascript -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`](#codepushgetupdatemetadata) instead, since it has more predictable behavior.* - -```javascript -codePush.getCurrentPackage(): Promise; -``` - -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 - 1. 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`](#localpackage) instance which represents the metadata for the currently running CodePush update. - -Example Usage: - -```javascript -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 - -```javascript -codePush.getUpdateMetadata(updateState: UpdateState = UpdateState.RUNNING): Promise; -``` - -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](#updatestate). - -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`](#localpackage) instance which represents the metadata for the currently requested CodePush update (either the running or pending). - -Example Usage: - -```javascript -// 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 - -```javascript -codePush.notifyAppReady(): Promise; -``` - -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 - -```javascript -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 - -```javascript -codePush.sync(options: Object, syncStatusChangeCallback: function(syncStatus: Number), downloadProgressCallback: function(progress: DownloadProgress)): Promise; -``` - -Synchronizes your app's JavaScript bundle and image assets with the latest release to the configured deployment. Unlike the [checkForUpdate](#codepushcheckforupdate) 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: - -```javascript -// 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](#codepushoptions), with the exception of the `checkFrequency` option: - -* __deploymentKey__ *(String)* - Refer to [`CodePushOptions`](#codepushoptions). - -* __installMode__ *(codePush.InstallMode)* - Refer to [`CodePushOptions`](#codepushoptions). - -* __mandatoryInstallMode__ *(codePush.InstallMode)* - Refer to [`CodePushOptions`](#codepushoptions). - -* __minimumBackgroundDuration__ *(Number)* - Refer to [`CodePushOptions`](#codepushoptions). - -* __updateDialog__ *(UpdateDialogOptions)* - Refer to [`CodePushOptions`](#codepushoptions). - -Example Usage: - -```javascript -// 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 two 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`](#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. - -Example Usage: - -```javascript -// 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__ *(4)* - The app is up-to-date with the CodePush server. - -* __codePush.SyncStatus.UPDATE_IGNORED__ *(5)* - 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__ *(6)* - 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__ *(7)* - 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 `` 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](#localpackage): Represents a downloaded update that is either already running, or has been installed and is pending an app restart. - -* [RemotePackage](#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`](#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. - -##### 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()`](#codepushsync) 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.CHECKING_FOR_UPDATE__ *(0)* - The CodePush server is being queried for an update. -* __codePush.SyncStatus.AWAITING_USER_ACTION__ *(1)* - 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__ *(2)* - An available update is being downloaded from the CodePush server. -* __codePush.SyncStatus.INSTALLING_UPDATE__ *(3)* - An available update was downloaded and is about to be installed. -* __codePush.SyncStatus.UP_TO_DATE__ *(4)* - The app is fully up-to-date with the configured deployment. -* __codePush.SyncStatus.UPDATE_IGNORED__ *(5)* - The app has an optional update, which the end user chose to ignore. (This is only applicable when the `updateDialog` is used) -* __codePush.SyncStatus.UPDATE_INSTALLED__ *(6)* - 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.SYNC_IN_PROGRESS__ *(7)* - There is an ongoing `sync` operation running which prevents the current call from being executed. -* __codePush.SyncStatus.UNKNOWN_ERROR__ *(-1)* - The sync operation encountered an unknown error. - -##### 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. - -### Objective-C API Reference (iOS) - -The Objective-C API is made available by importing the `CodePush.h` header into your `AppDelegate.m` file, and consists of a single public class named `CodePush`. - -#### CodePush - -Contains static methods for retreiving the `NSURL` that represents the most recent JavaScript bundle file, and can be passed to the `RCTRootView`'s `initWithBundleURL` method when bootstrapping your app in the `AppDelegate.m` file. - -The `CodePush` class' methods can be thought of as composite resolvers which always load the appropriate bundle, in order to accommodate the following scenarios: - -1. When an end-user installs your app from the store (e.g. `1.0.0`), they will get the JS bundle that is contained within the binary. This is the behavior you would get without using CodePush, but we make sure it doesn't break :) - -2. As soon as you begin releasing CodePush updates, your end-users will get the JS bundle that represents the latest release for the configured deployment. This is the behavior that allows you to iterate beyond what you shipped to the store. - -3. As soon as you release an update to the app store (e.g. `1.1.0`), and your end-users update it, they will once again get the JS bundle that is contained within the binary. This behavior ensures that CodePush updates that targetted a previous app store version aren't used (since we don't know it they would work), and your end-users always have a working version of your app. - -4. Repeat #2 and #3 as the CodePush releases and app store releases continue on into infinity (and beyond?) - -Because of this behavior, you can safely deploy updates to both the app store(s) and CodePush as necesary, and rest assured that your end-users will always get the most recent version. - -##### Methods - -- __(NSURL \*)bundleURL__ - Returns the most recent JS bundle `NSURL` as described above. This method assumes that the name of the JS bundle contained within your app binary is `main.jsbundle`. - -- __(NSURL \*)bundleURLForResource:(NSString \*)resourceName__ - Equivalent to the `bundleURL` method, but also allows customizing the name of the JS bundle that is looked for within the app binary. This is useful if you aren't naming this file `main` (which is the default convention). This method assumes that the JS bundle's extension is `*.jsbundle`. - -- __(NSURL \*)bundleURLForResource:(NSString \*)resourceName withExtension:(NSString \*)resourceExtension__: Equivalent to the `bundleURLForResource:` method, but also allows customizing the extension used by the JS bundle that is looked for within the app binary. This is useful if you aren't naming this file `*.jsbundle` (which is the default convention). - -- __(void)overrideAppVersion:(NSString \*)appVersionOverride__ - Sets the version of the application's binary interface, which would otherwise default to the App Store version specified as the `CFBundleShortVersionString` in the `Info.plist`. This should be called a single time, before the bundle URL is loaded. - -- __(void)setDeploymentKey:(NSString \*)deploymentKey__ - Sets the deployment key that the app should use when querying for updates. This is a dynamic alternative to setting the deployment key in your `Info.plist` and/or specifying a deployment key in JS when calling `checkForUpdate` or `sync`. - -### Java API Reference (Android) - -The Java API is made available by importing the `com.microsoft.codepush.react.CodePush` class into your `MainActivity.java` file, and consists of a single public class named `CodePush`. - -#### CodePush - -Constructs the CodePush client runtime and represents the `ReactPackage` instance that you add to you app's list of packages. - -##### Constructors - -- __CodePush(String deploymentKey, Activity mainActivity)__ - Creates a new instance of the CodePush runtime, that will be used to query the service for updates via the provided deployment key. The `mainActivity` parameter should always be set to `this` when configuring your React packages list inside the `MainActivity` class. This constructor puts the CodePush runtime into "release mode", so if you want to enable debugging behavior, use the following constructor instead. - -- __CodePush(String deploymentKey, Activity mainActivity, bool isDebugMode)__ - Equivalent to the previous constructor, but allows you to specify whether you want the CodePush runtime to be in debug mode or not. When using this constructor, the `isDebugMode` parameter should always be set to `BuildConfig.DEBUG` in order to stay synchronized with your build type. When putting CodePush into debug mode, the following behaviors are enabled: - - 1. Old CodePush updates aren't deleted from storage whenever a new binary is deployed to the emulator/device. This behavior enables you to deploy new binaries, without bumping the version during development, and without continuously getting the same update every time your app calls `sync`. - - 2. The local cache that the React Native runtime maintains in debug mode is deleted whenever a CodePush update is installed. This ensures that when the app is restarted after an update is applied, you will see the expected changes. As soon as [this PR](https://github.com/facebook/react-native/pull/4738) is merged, we won't need to do this anymore. - -##### Static Methods - -- __getBundleUrl()__ - Returns the path to the most recent version of your app's JS bundle file, assuming that the resource name is `index.android.bundle`. If your app is using a different bundle name, then use the overloaded version of this method which allows specifying it. This method has the same resolution behavior as the Objective-C equivalent described above. - -- __getBundleUrl(String bundleName)__ - Returns the path to the most recent version of your app's JS bundle file, using the specified resource name (e.g. `index.android.bundle`). This method has the same resolution behavior as the Objective-C equivalent described above. - -- __overrideAppVersion(String appVersionOverride)__ - Sets the version of the application's binary interface, which would otherwise default to the Play Store version specified as the `versionName` in the `build.gradle`. This should be called a single time, before the CodePush instance is constructed. - ## Example Apps / Starters The React Native community has graciously created some awesome open source apps that can serve as examples for developers that are getting started. The following is a list of OSS React Native apps that are also using CodePush, and can therefore be used to see how others are using the service: diff --git a/docs/api-android.md b/docs/api-android.md new file mode 100644 index 000000000..d61e17c5c --- /dev/null +++ b/docs/api-android.md @@ -0,0 +1,26 @@ + +### Java API Reference (Android) + +The Java API is made available by importing the `com.microsoft.codepush.react.CodePush` class into your `MainActivity.java` file, and consists of a single public class named `CodePush`. + +#### CodePush + +Constructs the CodePush client runtime and represents the `ReactPackage` instance that you add to you app's list of packages. + +##### Constructors + +- __CodePush(String deploymentKey, Activity mainActivity)__ - Creates a new instance of the CodePush runtime, that will be used to query the service for updates via the provided deployment key. The `mainActivity` parameter should always be set to `this` when configuring your React packages list inside the `MainActivity` class. This constructor puts the CodePush runtime into "release mode", so if you want to enable debugging behavior, use the following constructor instead. + +- __CodePush(String deploymentKey, Activity mainActivity, bool isDebugMode)__ - Equivalent to the previous constructor, but allows you to specify whether you want the CodePush runtime to be in debug mode or not. When using this constructor, the `isDebugMode` parameter should always be set to `BuildConfig.DEBUG` in order to stay synchronized with your build type. When putting CodePush into debug mode, the following behaviors are enabled: + + 1. Old CodePush updates aren't deleted from storage whenever a new binary is deployed to the emulator/device. This behavior enables you to deploy new binaries, without bumping the version during development, and without continuously getting the same update every time your app calls `sync`. + + 2. The local cache that the React Native runtime maintains in debug mode is deleted whenever a CodePush update is installed. This ensures that when the app is restarted after an update is applied, you will see the expected changes. As soon as [this PR](https://github.com/facebook/react-native/pull/4738) is merged, we won't need to do this anymore. + +##### Static Methods + +- __getBundleUrl()__ - Returns the path to the most recent version of your app's JS bundle file, assuming that the resource name is `index.android.bundle`. If your app is using a different bundle name, then use the overloaded version of this method which allows specifying it. This method has the same resolution behavior as the Objective-C equivalent described above. + +- __getBundleUrl(String bundleName)__ - Returns the path to the most recent version of your app's JS bundle file, using the specified resource name (e.g. `index.android.bundle`). This method has the same resolution behavior as the Objective-C equivalent described above. + +- __overrideAppVersion(String appVersionOverride)__ - Sets the version of the application's binary interface, which would otherwise default to the Play Store version specified as the `versionName` in the `build.gradle`. This should be called a single time, before the CodePush instance is constructed. diff --git a/docs/api-ios.md b/docs/api-ios.md new file mode 100644 index 000000000..e16c4044d --- /dev/null +++ b/docs/api-ios.md @@ -0,0 +1,32 @@ + +### Objective-C API Reference (iOS) + +The Objective-C API is made available by importing the `CodePush.h` header into your `AppDelegate.m` file, and consists of a single public class named `CodePush`. + +#### CodePush + +Contains static methods for retreiving the `NSURL` that represents the most recent JavaScript bundle file, and can be passed to the `RCTRootView`'s `initWithBundleURL` method when bootstrapping your app in the `AppDelegate.m` file. + +The `CodePush` class' methods can be thought of as composite resolvers which always load the appropriate bundle, in order to accommodate the following scenarios: + +1. When an end-user installs your app from the store (e.g. `1.0.0`), they will get the JS bundle that is contained within the binary. This is the behavior you would get without using CodePush, but we make sure it doesn't break :) + +2. As soon as you begin releasing CodePush updates, your end-users will get the JS bundle that represents the latest release for the configured deployment. This is the behavior that allows you to iterate beyond what you shipped to the store. + +3. As soon as you release an update to the app store (e.g. `1.1.0`), and your end-users update it, they will once again get the JS bundle that is contained within the binary. This behavior ensures that CodePush updates that targetted a previous app store version aren't used (since we don't know it they would work), and your end-users always have a working version of your app. + +4. Repeat #2 and #3 as the CodePush releases and app store releases continue on into infinity (and beyond?) + +Because of this behavior, you can safely deploy updates to both the app store(s) and CodePush as necesary, and rest assured that your end-users will always get the most recent version. + +##### Methods + +- __(NSURL \*)bundleURL__ - Returns the most recent JS bundle `NSURL` as described above. This method assumes that the name of the JS bundle contained within your app binary is `main.jsbundle`. + +- __(NSURL \*)bundleURLForResource:(NSString \*)resourceName__ - Equivalent to the `bundleURL` method, but also allows customizing the name of the JS bundle that is looked for within the app binary. This is useful if you aren't naming this file `main` (which is the default convention). This method assumes that the JS bundle's extension is `*.jsbundle`. + +- __(NSURL \*)bundleURLForResource:(NSString \*)resourceName withExtension:(NSString \*)resourceExtension__: Equivalent to the `bundleURLForResource:` method, but also allows customizing the extension used by the JS bundle that is looked for within the app binary. This is useful if you aren't naming this file `*.jsbundle` (which is the default convention). + +- __(void)overrideAppVersion:(NSString \*)appVersionOverride__ - Sets the version of the application's binary interface, which would otherwise default to the App Store version specified as the `CFBundleShortVersionString` in the `Info.plist`. This should be called a single time, before the bundle URL is loaded. + +- __(void)setDeploymentKey:(NSString \*)deploymentKey__ - Sets the deployment key that the app should use when querying for updates. This is a dynamic alternative to setting the deployment key in your `Info.plist` and/or specifying a deployment key in JS when calling `checkForUpdate` or `sync`. diff --git a/docs/api-js.md b/docs/api-js.md new file mode 100644 index 000000000..1f04edcf0 --- /dev/null +++ b/docs/api-js.md @@ -0,0 +1,565 @@ + +## 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](#codepush): + +* [allowRestart](#codepushallowrestart): 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](#codepushcheckforupdate): Asks the CodePush service whether the configured app deployment has an update available. + +* [disallowRestart](#codepushdisallowrestart): 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](#codepushgetcurrentpackage): 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`](#codepushgetupdatemetadata)*. + +* [getUpdateMetadata](#codepushgetupdatemetadata): Retrieves the metadata for an installed update (e.g. description, mandatory). + +* [notifyAppReady](#codepushnotifyappready): 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](#codepushsync) 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](#codepushrestartapp): 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](#codepushsync): 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 + +#### codePush + +```javascript +// Wrapper function +codePush(rootComponent: React.Component): React.Component; +codePush(options: CodePushOptions)(rootComponent: React.Component): React.Component; +``` +```javascript +// 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`](#codepushsync) 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. + + ```javascript + // 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); + ``` + +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". + + ```javascript + // 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); + ``` + +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. + + ```javascript + // 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); + ``` + +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. + + ```javascript + // 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); + ``` + +##### 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`](#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`](#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`](#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`, 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, 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](#user-content-apple-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`](#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 + +```javascript +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](#codepushdisallowrestart) 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](#codepushdisallowrestart) for an example of how this method can be used. + +#### codePush.checkForUpdate + +```javascript +codePush.checkForUpdate(deploymentKey: String = null): Promise; +``` + +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. + +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`](#remotepackage) instance which represents an available update that can be inspected and/or subsequently downloaded. + +Example Usage: + +```javascript +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 + +```javascript +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: + +```javascript +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`](#codepushgetupdatemetadata) instead, since it has more predictable behavior.* + +```javascript +codePush.getCurrentPackage(): Promise; +``` + +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 + 1. 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`](#localpackage) instance which represents the metadata for the currently running CodePush update. + +Example Usage: + +```javascript +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 + +```javascript +codePush.getUpdateMetadata(updateState: UpdateState = UpdateState.RUNNING): Promise; +``` + +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](#updatestate). + +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`](#localpackage) instance which represents the metadata for the currently requested CodePush update (either the running or pending). + +Example Usage: + +```javascript +// 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 + +```javascript +codePush.notifyAppReady(): Promise; +``` + +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 + +```javascript +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 + +```javascript +codePush.sync(options: Object, syncStatusChangeCallback: function(syncStatus: Number), downloadProgressCallback: function(progress: DownloadProgress)): Promise; +``` + +Synchronizes your app's JavaScript bundle and image assets with the latest release to the configured deployment. Unlike the [checkForUpdate](#codepushcheckforupdate) 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: + +```javascript +// 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](#codepushoptions), with the exception of the `checkFrequency` option: + +* __deploymentKey__ *(String)* - Refer to [`CodePushOptions`](#codepushoptions). + +* __installMode__ *(codePush.InstallMode)* - Refer to [`CodePushOptions`](#codepushoptions). + +* __mandatoryInstallMode__ *(codePush.InstallMode)* - Refer to [`CodePushOptions`](#codepushoptions). + +* __minimumBackgroundDuration__ *(Number)* - Refer to [`CodePushOptions`](#codepushoptions). + +* __updateDialog__ *(UpdateDialogOptions)* - Refer to [`CodePushOptions`](#codepushoptions). + +Example Usage: + +```javascript +// 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 two 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`](#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. + +Example Usage: + +```javascript +// 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__ *(4)* - The app is up-to-date with the CodePush server. + +* __codePush.SyncStatus.UPDATE_IGNORED__ *(5)* - 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__ *(6)* - 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__ *(7)* - 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 `` 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](#localpackage): Represents a downloaded update that is either already running, or has been installed and is pending an app restart. + +* [RemotePackage](#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`](#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. + +##### 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()`](#codepushsync) 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.CHECKING_FOR_UPDATE__ *(0)* - The CodePush server is being queried for an update. +* __codePush.SyncStatus.AWAITING_USER_ACTION__ *(1)* - 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__ *(2)* - An available update is being downloaded from the CodePush server. +* __codePush.SyncStatus.INSTALLING_UPDATE__ *(3)* - An available update was downloaded and is about to be installed. +* __codePush.SyncStatus.UP_TO_DATE__ *(4)* - The app is fully up-to-date with the configured deployment. +* __codePush.SyncStatus.UPDATE_IGNORED__ *(5)* - The app has an optional update, which the end user chose to ignore. (This is only applicable when the `updateDialog` is used) +* __codePush.SyncStatus.UPDATE_INSTALLED__ *(6)* - 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.SYNC_IN_PROGRESS__ *(7)* - There is an ongoing `sync` operation running which prevents the current call from being executed. +* __codePush.SyncStatus.UNKNOWN_ERROR__ *(-1)* - The sync operation encountered an unknown error. + +##### 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. diff --git a/docs/setup-android.md b/docs/setup-android.md new file mode 100644 index 000000000..0909bfd00 --- /dev/null +++ b/docs/setup-android.md @@ -0,0 +1,188 @@ + +## Android Setup + +In order to integrate CodePush into your Android project, 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**](#plugin-installation-android---rnpm) - [React Native Package Manager (RNPM)](https://github.com/rnpm/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"**](#plugin-installation-android---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 -k`, or you can choose to ignore it (by simply hitting ``) 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](#plugin-configuration-android) section to complete the setup. + +#### Plugin Installation (Android - Manual) + +1. In your `android/settings.gradle` file, make the following additions: + + ```gradle + 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: + + ```gradle + ... + 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`: + + ```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** + +Update the `MainApplication.java` file to use CodePush via the following changes: + +```java +... +// 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 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 -k" to retrieve your key. + return Arrays.asList( + new MainReactPackage(), + new CodePush("deployment-key-here", MainApplication.this, BuildConfig.DEBUG) + ); + } + }; +} +``` + +**For React Native v0.19 - v0.28** + +Update the `MainActivity.java` file to use CodePush via the following changes: + +```java +... +// 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 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 -k" to retrieve your key. + return Arrays.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** + +Update the `MainApplication.java` file to use CodePush via the following changes: + +```java +... +// 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** + +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: + +```java +// 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](../README.md#multi-deployment-testing) docs below before actually moving your app's usage of CodePush into production. diff --git a/docs/setup-ios.md b/docs/setup-ios.md new file mode 100644 index 000000000..a4e46b158 --- /dev/null +++ b/docs/setup-ios.md @@ -0,0 +1,119 @@ +## iOS Setup + +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**](#plugin-installation-ios---rnpm) - [React Native Package Manager (RNPM)](https://github.com/rnpm/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**](#plugin-installation-ios---cocoapods) - If you're building a native iOS app that is embedding React Native into it, or you simply prefer using [CocoaPods](https://cocoapods.org), then we recommend using the Podspec file that we ship as part of our plugin. + +3. [**"Manual"**](#plugin-installation-ios---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 -k`, or you can choose to ignore it (by simply hitting ``) 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 CodePush plugin dependency to your `Podfile`, pointing at the path where NPM installed it + + ```ruby + pod 'CodePush', :path => '../node_modules/react-native-code-push' + ``` + + CodePush depends on an internal copy of the `SSZipArchive` library, so if your project already includes it (either directly or via a transitive dependency), then you can install a version of CodePush which excludes it by depending specifically on the `Core` subspec: + + ```ruby + pod 'CodePush', :path => '../node_modules/react-native-code-push', :subspecs => ['Core'] + ``` + + *NOTE: The above paths needs to be relative to your app's `Podfile`, so adjust it as nec + cessary.* + +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](https://facebook.github.io/react-native/docs/integration-with-existing-apps.html#podfile).* + +#### 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](https://cloud.githubusercontent.com/assets/8598682/13368613/c5c21422-dca0-11e5-8594-c0ec5bde9d81.png) + +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](https://cloud.githubusercontent.com/assets/516559/10322221/a75ea066-6c31-11e5-9d88-ff6f6a4d6968.png) + +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](https://cloud.githubusercontent.com/assets/116461/11605042/6f786e64-9aaa-11e5-8ca7-14b852f808b1.png) + + *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: + + ```objective-c + #import + ``` + +2. Find the following line of code, which loads your JS Bundle from the app binary for production releases: + + ```objective-c + jsCodeLocation = [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"]; + ``` + +3. Replace it with this line: + + ```objective-c + 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. + +```objective-c +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 -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](https://cloud.githubusercontent.com/assets/116461/11601733/13011d5e-9a8a-11e5-9ce2-b100498ffb34.png) + +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](../README.md#multi-deployment-testing) docs below before actually moving your app's usage of CodePush into production. diff --git a/docs/setup-windows.md b/docs/setup-windows.md new file mode 100644 index 000000000..515aec7b4 --- /dev/null +++ b/docs/setup-windows.md @@ -0,0 +1,65 @@ +## Windows Setup + +Once you've acquired the CodePush plugin, you need to integrate it into the Visual Studio project of your React Native app and configure it correctly. To do this, take the following steps: + +### Plugin Installation (Windows) + +1. Open the Visual Studio solution located at `windows\\.sln` within your app + +2. Right-click the solution node in the `Solution Explorer` window and select the `Add -> Existing Project...` menu item + + ![Add Project](https://cloud.githubusercontent.com/assets/116461/14467164/ddf6312e-008e-11e6-8a10-44a8b44b5dfc.PNG) + +3. Browse to the `node_modules\react-native-code-push\windows` directory, select the `CodePush.csproj` file and click `OK` + +4. Back in the `Solution Explorer`, right-click the project node that is named after your app, and select the `Add -> Reference...` menu item + + ![Add Reference](https://cloud.githubusercontent.com/assets/116461/14467154/d833bc98-008e-11e6-8e95-09864b1f05ef.PNG) + +5. Select the `Projects` tab on the left hand side, check the `CodePush` item and then click `OK` + + ![Add Reference Dialog](https://cloud.githubusercontent.com/assets/116461/14467147/cb805b6e-008e-11e6-964f-f856c59b65af.PNG) + +### Plugin Configuration (Windows) + +After installing the plugin, 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, update the `AppReactPage.cs` file to use CodePush via the following changes: + +```c# +... +// 1. Import the CodePush namespace +using CodePush.ReactNative; +... +class AppReactPage : ReactPage +{ + // 2. Declare a private instance variable for the CodePushModule instance. + private CodePushReactPackage codePushReactPackage; + + // 3. Update the JavaScriptBundleFile property to initalize the CodePush runtime, + // specifying the right deployment key, then use it to return the bundle URL from + // CodePush instead of statically from the binary. If you don't already have your + // deployment key, you can run "code-push deployment ls -k" to retrieve it. + public override string JavaScriptBundleFile + { + get + { + codePushReactPackage = new CodePushReactPackage("deployment-key-here", this); + return codePushReactPackage.GetJavaScriptBundleFile(); + } + } + + // 4. Add the codePushReactPackage instance to the list of existing packages. + public override List Packages + { + get + { + return new List + { + new MainReactPackage(), + ... + codePushReactPackage + }; + } + } + ... +} +```