React Native Client SDK API Reference
Important
Visual Studio App Center is scheduled for retirement on March 31, 2025. While you can continue to use Visual Studio App Center until it is fully retired, there are several recommended alternatives that you may consider migrating to.
The CodePush plugin is made up of two components:
A JavaScript module, which can be imported/required, and allows the app to interact with the service during runtime (for example check for updates, inspect the metadata about the currently running app update).
A native API (Objective-C and Java) that allows the React Native app host to bootstrap itself with the right JS bundle location.
The following sections describe the shape and behavior of these APIs in detail:
JavaScript API Reference
When you require react-native-code-push
, the module object provides the following top-level methods in addition to the root-level component decorator:
allowRestart: Reallows 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 method is an advanced API and is only necessary if your app explicitly disallowed restarts via the
disallowRestart
method.checkForUpdate: Asks the CodePush service whether the configured app deployment has an update available.
disallowRestart: Temporarily disallows any programmatic restarts to occur as a result of a CodePush update being installed. This method is an advanced API, and is useful when a component within your app (for example an onboarding process) needs to ensure that no end-user interruptions can occur during its lifetime.
getCurrentPackage: Retrieves the metadata about the currently installed update (like description, installation time, size).
Note
As of
v1.10.3-beta
of the CodePush module,getCurrentPackage
is deprecated in favor ofgetUpdateMetadata
*.getUpdateMetadata: Retrieves the metadata for an installed update (like description, mandatory).
notifyAppReady: Notifies the CodePush runtime that an installed update is considered successful. If you're manually checking for and installing updates (that isn't using the sync method to handle it all for you), then this method MUST be called; otherwise CodePush will treat the update as failed and roll back to the previous version when the app next restarts.
restartApp: Immediately restarts the app. If there's an update pending, it will be immediately displayed to the end user. Otherwise, calling this method has the same behavior as the end user killing and restarting the process.
sync: Allows checking for an update, downloading it and installing it, all with a single call. Unless you need custom UI or behavior, we recommend most developers to use this method when integrating CodePush into their apps
codePush
// Wrapper function
codePush(rootComponent: React.Component): React.Component;
codePush(options: CodePushOptions)(rootComponent: React.Component): React.Component;
// Decorator; Requires ES7 support
@codePush
@codePush(options: CodePushOptions)
Used to wrap a React component inside a "higher order" React component that knows how to synchronize your app's JavaScript bundle and image assets when it's mounted. Internally, the higher-order component calls sync
inside its componentDidMount
lifecycle handle, which runs an update check, downloads the update if it exists, and installs the update for you.
This decorator provides support for letting you customize its behavior 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):
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 (like 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 or "synthetic" app restarts.
// Fully silent update that keeps the app in // sync with the server, without ever // interrupting the end user class MyApp extends Component {} MyApp = codePush(MyApp);
Silent sync every time the app resumes. Same as 1, except we check for updates, or apply an update if one exists every time the app returns to the foreground after being "backgrounded".
// Sync for updates every time the app resumes. class MyApp extends Component {} MyApp = codePush({ checkFrequency: codePush.CheckFrequency.ON_APP_RESUME, installMode: codePush.InstallMode.ON_NEXT_RESUME })(MyApp);
Interactive. When an update is available, prompt the end user for permission before downloading it, and then immediately apply the update. If an update was released using the
mandatory
flag, the end user would still be notified about the update, but they wouldn't have the choice to ignore it.// Active update that 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);
Log/display progress. While the app is syncing with the server for updates, make use of the
codePushStatusDidChange
orcodePushDownloadDidProgress
event hooks to log down the different stages of this process, or even display a progress bar to the user.// Make use of the event hooks to keep track of // the different stages of the sync process. class MyApp extends Component { codePushStatusDidChange(status) { switch(status) { case codePush.SyncStatus.CHECKING_FOR_UPDATE: console.log("Checking for updates."); break; case codePush.SyncStatus.DOWNLOADING_PACKAGE: console.log("Downloading package."); break; case codePush.SyncStatus.INSTALLING_UPDATE: console.log("Installing update."); break; case codePush.SyncStatus.UP_TO_DATE: console.log("Up-to-date."); break; case codePush.SyncStatus.UPDATE_INSTALLED: console.log("Update installed."); break; } } codePushDownloadDidProgress(progress) { console.log(progress.receivedBytes + " of " + progress.totalBytes + " received."); } } MyApp = codePush(MyApp);
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 want to check for updates. Defaults to
codePush.CheckFrequency.ON_APP_START
. Refer to theCheckFrequency
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 want to install optional updates (those that aren't marked as mandatory). Defaults to
codePush.InstallMode.ON_NEXT_RESTART
. Refer to theInstallMode
enum reference for a description of the available options and what they do.mandatoryInstallMode (codePush.InstallMode) - Specifies when you want to install updates, which are marked as mandatory. Defaults to
codePush.InstallMode.IMMEDIATE
. Refer to theInstallMode
enum reference for a description of the available options and what they do.minimumBackgroundDuration (Number) - Specifies the minimum number of seconds for the app to be in the background before restarting the app. This property only applies to updates that are installed using
InstallMode.ON_NEXT_RESUME
orInstallMode.ON_NEXT_SUSPEND
, and can be useful for getting your update in front of end users sooner, without being too obtrusive. Defaults to0
, which applies the update immediately after a resume, or unless the app suspension is long enough to not matter, however long it's 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 disables the dialog. Setting this to anytrue
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, see this note.The following list represents the available options and their defaults:
appendReleaseDescription (Boolean) - Indicates whether you want 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 want 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 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 to ignore an optional update that's available. Defaults to
"Ignore"
.optionalInstallButtonLabel (String) - The text to use for the button the end user can press 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's displayed to the end user. Defaults to
"Update available"
.
rollbackRetryOptions (RollbackRetryOptions) - The rollback retry mechanism allows the application to attempt to reinstall an update that was previously rolled back (with the restrictions specified in the options). It is an "options" object used to determine whether a rollback retry should occur, and if so, what settings to use for the rollback retry. This defaults to null, which has the effect of disabling the retry mechanism. Setting this to any truthy value will enable the retry mechanism with the default settings, and passing an object to this parameter allows enabling the rollback retry as well as overriding one or more of the default values.
The following list represents the available options and their defaults:
delayInHours (Number) - Specifies the minimum time in hours that the app will wait after the latest rollback before attempting to reinstall the same rolled-back package. Cannot be less than
0
. Can be float number. Defaults to24
.maxRetryAttempts (Number) - Specifies the maximum number of retry attempts that the app can make before it stops trying. Cannot be less than
1
. Defaults to1
.
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 that represents the current state, and can be any of the SyncStatus
values.
codePushDownloadDidProgress (event hook)
Called periodically when an available update is being downloaded from the CodePush server. The method is called with a DownloadProgress
object, which contains the following two properties:
totalBytes (Number) - The total number of bytes expected to be received for this update (that's the size of the set of files, which changed from the previous release).
receivedBytes (Number) - The number of bytes downloaded thus far, which can be used to track download progress.
codePush.allowRestart
codePush.allowRestart(): void;
Reallows programmatic restarts to occur, that would've otherwise been rejected because of a previous call to disallowRestart
. If disallowRestart
was never called in the first place, then calling this method results in a no-op.
If a CodePush update is currently pending, which attempted to restart the app (for example it used InstallMode.IMMEDIATE
), but was blocked because of disallowRestart
having been called, then calling allowRestart
will result in an immediate restart. This restart allows the update to be applied as soon as possible, without interrupting the end user during critical workflows (for example an onboarding process).
For example, calling allowRestart
would trigger an immediate restart if either of the three scenarios mentioned in the disallowRestart
docs occurred after disallowRestart
was called. However, calling allowRestart
wouldn't trigger a restart if the following points are true:
No CodePush updates were installed since the last time
disallowRestart
was called, and so, there isn't any need to restart anyways.There's currently a pending CodePush update, but it was installed via
InstallMode.ON_NEXT_RESTART
, so a programmatic restart isn't required.There's 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, so there's no need to programmatically restart yet.No calls to
restartApp
were made since the last timedisallowRestart
was called.
This behavior ensures that no restarts will be triggered as a result of calling allowRestart
unless one was explicitly requested during the disallowed period. In this way, allowRestart
is similar to calling restartApp(true)
, except the former will only trigger a restart if the currently pending update wanted to restart, but the latter would restart as long as an update is pending.
See disallowRestart for an example of how this method can be used.
codePush.checkForUpdate
codePush.checkForUpdate(deploymentKey: String = null, handleBinaryVersionMismatchCallback: (update: RemotePackage) => void): Promise<RemotePackage>;
Queries the CodePush service to see whether the configured app deployment has an update available. By default, it will use the deployment key that's configured in your Info.plist file (iOS), or MainActivity.java file (Android), but you can override that by specifying a value via the optional deploymentKey
parameter. This can be useful when you want to dynamically "redirect" a user to a specific deployment, such as allowing "early access" via an easter egg or a user setting switch.
Second optional parameter handleBinaryVersionMismatchCallback
is an optional callback function that can be used to notify user if there are any binary update.
For example, consider a use-case where currently installed binary version is 1.0.1 with a label (code push label) v1. Later native code was changed in the dev cycle and the binary version was updated to 1.0.2. When a codepush update check is triggered, we ignore updates having binary version mismatch (because the update isn't targeting to the binary version of currently installed app). In this case, installed app (1.0.1) will ignore the update targeting version 1.0.2. You can use handleBinaryVersionMismatchCallback
to provide a hook to handle such situations.
Important
Be cautious to use Alerts within this callback if you're developing iOS application, because of App Store review process: Apps must not force users to rate the app, review the app, download other apps, or other similar actions to access functionality, content, or use of the app.
This method returns a Promise
, which resolves to one of two possible values:
null
if there isn't an update available. This can occur in the following scenarios:- The configured deployment doesn't contain any releases, and so, nothing to update.
- The latest release within the configured deployment is targeting a different binary version than what you're currently running (either older or newer).
- The currently running app already has the latest release from the configured deployment, and so, doesn't need it again.
- The latest release within the configured deployment is currently marked as disabled, so it isn't allowed to be downloaded.
- 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.
A
RemotePackage
instance, which represents an available update that can be inspected or later downloaded.
Example Usage:
codePush.checkForUpdate()
.then((update) => {
if (!update) {
console.log("The app is up to date!");
} else {
console.log("An update is available! Should we download it?");
}
});
codePush.disallowRestart
codePush.disallowRestart(): void;
Temporarily disallows programmatic restarts to occur as a result of either of following scenarios:
A CodePush update is installed using
InstallMode.IMMEDIATE
A CodePush update is installed using
InstallMode.ON_NEXT_RESUME
and the app is resumed from the background (optionally being throttled by theminimumBackgroundDuration
property)The
restartApp
method was calledNote
Steps 1 and 2 effectively work by calling
restartApp
for you, so you can think ofdisallowRestart
as blocking any call torestartApp
, whether 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 (like 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 use InstallMode.ON_NEXT_RESTART
whenever calling sync
(which will never attempt to programmatically restart the app), and then explicitly calling restartApp
at points in your app that's "safe" to do so. disallowRestart
provides an alternative approach to this when the code that synchronizes with the CodePush server is separate from the code/components that want to enforce a no-restart policy.
Example Usage:
class OnboardingProcess extends Component {
...
componentWillMount() {
// Ensure that any CodePush updates that 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 recommend using the codePush.getUpdateMetadata
instead, since it has more predictable behavior.
codePush.getCurrentPackage(): Promise<LocalPackage>;
Retrieves the metadata about the currently installed "package" (like 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's a pending update that's waiting to be applied via a resume or restart.
This method returns a Promise
, which resolves to one of two possible values:
null
if the app is currently running the JS bundle from the binary and not a CodePush update. This occurs in the following scenarios:- The end user installed the app binary and has yet to install a CodePush update
- The end user installed an update of the binary (for example from the store), which cleared away the old CodePush updates, and gave precedence back to the JS binary in the binary.
A
LocalPackage
instance, which represents the metadata for the currently running CodePush update.
Example Usage:
codePush.getCurrentPackage()
.then((update) => {
// If the current app "session" represents the first time
// this update has run, and it had a description provided
// with it upon release, let's show it to the end user
if (update.isFirstRun && update.description) {
// Display a "what's new?" modal
}
});
codePush.getUpdateMetadata
codePush.getUpdateMetadata(updateState: UpdateState = UpdateState.RUNNING): Promise<LocalPackage>;
Retrieves the metadata for an installed update (like 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's a pending update that's waiting to be applied via a resume or restart. For more information about the possible update states, and what they represent, see to the UpdateState reference.
This method returns a Promise
, which resolves to one of two possible values:
null
if an update with the specified state doesn't currently exist. This occurs in the following scenarios:The end user hasn't installed any CodePush updates yet, and that's why no metadata is available for any updates, whatever you specify as the
updateState
parameter.The end user installed an update of the binary (for example from the store), which cleared away the old CodePush updates, and gave precedence back to the JS binary in the binary. It would exhibit the same behavior as #1
The
updateState
parameter is set toUpdateState.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 to make it active.The
updateState
parameter is set toUpdateState.PENDING
, but the app doesn't have any currently pending updates.
A
LocalPackage
instance, which represents the metadata for the currently requested CodePush update (either the running or pending).
Example Usage:
// Check if there's 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's still an update pending.
codePush.getUpdateMetadata(UpdateState.PENDING).then((update) => {
if (update) {
// There's a pending update, do we want to force a restart?
}
});
codePush.notifyAppReady
codePush.notifyAppReady(): Promise<void>;
Notifies the CodePush runtime that a freshly installed update should be considered successful, and so, an automatic client-side roll back isn't necessary. It's 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're 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 because of the assumption that when sync
is called in your app, it represents a good approximation of a successful startup.
Note
This method is also aliased as notifyApplicationReady
(for backwards compatibility).
codePush.restartApp
codePush.restartApp(onlyIfUpdateIsPending: Boolean = false): void;
Immediately restarts the app. If a truth value is provided to the onlyIfUpdateIsPending
parameter, then the app will only restart if there's actually a pending update waiting to be applied.
This method is for advanced scenarios, and is primarily useful when the following conditions are true:
Your app is specifying an install mode value of
ON_NEXT_RESTART
orON_NEXT_RESUME
when calling thesync
orLocalPackage.install
methods. This doesn't apply your update until the app has restarted (by either the end user or OS) or resumed, and so, the update won't be immediately displayed to the end user.You have an app-specific user event (like 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 to the end user sooner than waiting until the next restart or resume.
codePush.sync
codePush.sync(options: Object, syncStatusChangeCallback: function(syncStatus: Number), downloadProgressCallback: function(progress: DownloadProgress), handleBinaryVersionMismatchCallback: function(update: RemotePackage)): Promise<Number>;
Synchronizes your app's JavaScript bundle and image assets with the latest release to the configured deployment. Unlike the checkForUpdate method, which 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:
Silent mode (the default behavior) automatically downloads available updates, and applies them the next time the app restarts (for example 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 or "synthetic" app restarts.
Active mode, which when an update is available, prompts the end user for permission before downloading it, and then immediately applies the update. If an update was released using the
mandatory
flag, the end user would still be notified about the update, but they wouldn't have the choice to ignore it.
Example Usage:
// Fully silent update that 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 });
Tip
If you want to decide whether you check or download an available update based on the end user's device battery level, network conditions, etc. then wrap the call to sync
in a condition that ensures you only call it when wanted.
SyncOptions
While the sync
method tries to make it easy to do silent and active updates with little configuration, it accepts an "options" object that allows you to customize many aspects of the default behavior mentioned above. The options available are identical to the CodePushOptions, with the exception of the checkFrequency
option:
deploymentKey (String) - Refer to
CodePushOptions
.installMode (codePush.InstallMode) - Refer to
CodePushOptions
.mandatoryInstallMode (codePush.InstallMode) - Refer to
CodePushOptions
.minimumBackgroundDuration (Number) - Refer to
CodePushOptions
.updateDialog (UpdateDialogOptions) - Refer to
CodePushOptions
.rollbackRetryOptions (RollbackRetryOptions) - Refer to
CodePushOptions
.
Example Usage:
// Use a different deployment key for this
// specific call, instead of the one configured
// in the Info.plist file
codePush.sync({ deploymentKey: "KEY" });
// Download the update silently, but install it on
// the next resume, as long as at least 5 minutes
// has passed since the app was put into the background.
codePush.sync({ installMode: codePush.InstallMode.ON_NEXT_RESUME, minimumBackgroundDuration: 60 * 5 });
// Download the update silently, and install optional updates
// on the next restart, but install mandatory updates on the next resume.
codePush.sync({ mandatoryInstallMode: codePush.InstallMode.ON_NEXT_RESUME });
// Changing the title displayed in the
// confirmation dialog of an "active" update
codePush.sync({ updateDialog: { title: "An update is available!" } });
// Displaying an update prompt which includes the
// description for the CodePush release
codePush.sync({
updateDialog: {
appendReleaseDescription: true,
descriptionPrefix: "\n\nChange log:\n"
},
installMode: codePush.InstallMode.IMMEDIATE
});
// Shortening the retry delay and increasing
// the number of maximum retry attempts
// in comparison to defaults
codePush.sync({
rollbackRetryOptions: {
delayInHours: 8,
maxRetryAttempts: 3
}
});
In addition to the options, the sync
method also accepts several optional function parameters, which allow you to subscribe to the lifecycle of the sync
"pipeline" to display additional UI as needed (like a "checking for update modal or a download progress modal):
syncStatusChangedCallback ((syncStatus: Number) => void) - Called when the sync process moves from one stage to another in the overall update process. The method is called with a status code, which represents the current state, and can be any of the
SyncStatus
values.downloadProgressCallback ((progress: DownloadProgress) => void) - Called periodically when an available update is being downloaded from the CodePush server. The method is called with a
DownloadProgress
object, which contains the following two properties:totalBytes (Number) - The total number of bytes expected to be received for this update (that's the size of the set of files, which changed from the previous release).
receivedBytes (Number) - The number of bytes downloaded thus far, which can be used to track download progress.
handleBinaryVersionMismatchCallback ((update: RemotePackage) => void) - Called when there are any binary update available. The method is called with a
RemotePackage
object. See the codePush.checkForUpdate section for more details.
Example Usage:
// Prompt the user when an update is available
// and then display a "downloading" modal
codePush.sync({ updateDialog: true },
(status) => {
switch (status) {
case codePush.SyncStatus.DOWNLOADING_PACKAGE:
// Show "downloading" modal
break;
case codePush.SyncStatus.INSTALLING_UPDATE:
// Hide "downloading" modal
break;
}
},
({ receivedBytes, totalBytes, }) => {
/* Update download modal progress */
}
);
This method returns a Promise
, which is resolved to a SyncStatus
code that indicates why the sync
call succeeded. This code can be one of the following SyncStatus
values:
codePush.SyncStatus.UP_TO_DATE (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 theInstallMode
specified inSyncOptions
.codePush.SyncStatus.SYNC_IN_PROGRESS (7) - There's an ongoing
sync
operation running that prevents the current call from being executed.
The sync
method can be called anywhere you want to check for an update. That could be in the componentWillMount
lifecycle event of your root component, the onPress handler of a <TouchableHighlight>
component, in the callback of a periodic timer, or whatever else makes sense for your needs. Like the checkForUpdate
method, it does the network request to check for an update in the background, so it won't impact your UI thread or JavaScript thread's responsiveness.
Package objects
The checkForUpdate
and getUpdateMetadata
methods return Promise
objects, that when resolved, provide access to "package" objects. The package represents your code update and any extra metadata (like description, mandatory?). The CodePush API has the distinction between the following types of packages:
LocalPackage: Represents a downloaded update that's either already running, or has been installed and is pending an app restart.
RemotePackage: Represents an available update on the CodePush server that hasn't been downloaded yet.
LocalPackage
Contains details about an update that has been downloaded locally or already installed. You can get a reference to an instance of this object either by calling the module-level getUpdateMetadata
method, or as the value of the promise returned by the RemotePackage.download
method.
Properties
- appVersion: The app binary version that this update is dependent on. This is the value that was specified via the
appStoreVersion
parameter when calling the CLI'srelease
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 usingcheckForUpdate
. (Boolean) - isFirstRun: Indicates whether this is the first time the update has been run after being installed. This is useful for determining whether you want 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 that's why its 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 its 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 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 theInstallMode
enum reference for a description of the available options and what they do. If theinstallMode
parameter is set toInstallMode.ON_NEXT_RESUME
, then theminimumBackgroundDuration
parameter allows you to control how long the app must have been in the background before forcing the install after it's resumed.
RemotePackage
Contains details about an update that's 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're 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 where 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 aDownloadProgress
object ({ totalBytes: Number, receivedBytes: Number }
) that reports the progress of the download until it completes. Returns a Promise that resolves with theLocalPackage
.
Enums
The CodePush API includes the following enums, which can be used to customize the update experience:
InstallMode
This enum specifies when you want 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 unwanted 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 (because of the OS or end user killing it), the update will be seamlessly picked up. This value is appropriate when doing silent updates, since it's probably disruptive to the end user if the app suddenly restarts out of nowhere. They wouldn't realize an update was even downloaded. This is the default mode used for both the
sync
andLocalPackage.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 than having to wait for the next natural restart. This value is appropriate for silent installs that can be applied on resume in a non-invasive way.
codePush.InstallMode.ON_NEXT_SUSPEND (3) - Indicates that you want to install the update while it's in the background, but only after it's been in the background for
minimumBackgroundDuration
seconds (0 by default), so that user context isn't lost unless the app suspension is long enough to not matter.
CheckFrequency
This enum specifies when you want 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 separate payment process, and so on).
codePush.CheckFrequency.MANUAL (2) - Disable automatic checking for updates, but only check when
codePush.sync()
is called in app code.
SyncStatus
This enum is provided to the syncStatusChangedCallback
function that can be passed to the sync
method, 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 theInstallMode
specified inSyncOptions
. - codePush.SyncStatus.SYNC_IN_PROGRESS (7) - There's an ongoing
sync
operation preventing the current call from being executed. - codePush.SyncStatus.UNKNOWN_ERROR (-1) - The sync operation found 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's 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 or crash reporting service.
codePush.UpdateState.PENDING (1) - Indicates that an update has been installed, but the app hasn't been restarted yet to apply it. This can be useful for determining whether there's a pending update, which you may want to force a programmatic restart (via
restartApp
) to apply.codePush.UpdateState.LATEST (2) - Indicates that 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 retrieving 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, to accommodate the following scenarios:
When an end user installs your app from the store (like
1.0.0
), they'll get the JS bundle that's contained within the binary. This is the behavior you'd get without using CodePush, but we make sure it doesn't break :)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.
As soon as you release an update to the app store (like
1.1.0
), and your end users update it, they'll once again get the JS bundle that's contained within the binary. This behavior ensures that CodePush updates that targeted a previous binary 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.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 necessary, 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 ismain.jsbundle
.(NSURL *)bundleURLForResource:(NSString *)resourceName - Equivalent to the
bundleURL
method, but also allows customizing the name of the JS bundle that's searched for within the app binary. This is useful if you aren't naming this filemain
(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's searched 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 or specifying a deployment key in JS when calling
checkForUpdate
orsync
.
Java API Reference (Android)
API for React Native 0.60 version and above
Since autolinking
uses react-native.config.js
to link plugins, constructors are specified in that file. But you can override custom variables to manage the CodePush plugin by placing these values in string resources.
Public Key - used for bundle verification in the Code Signing Feature. See the Code Signing section for more details about the Code Signing Feature. To set the public key, you should add the content of the public key to
strings.xml
with nameCodePushPublicKey
. CodePush automatically gets this property and enables the Code Signing feature. For example:<string moduleConfig="true" name="CodePushPublicKey">your-public-key</string>
Server Url - used for specifying CodePush Server Url. The Default value: "https://codepush.appcenter.ms/" is overridden by adding your path to
strings.xml
with nameCodePushServerUrl
. CodePush automatically gets this property and will use this path to send requests. For example:<string moduleConfig="true" name="CodePushServerUrl">https://yourcodepush.server.com</string>
API for React Native lower than 0.60
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 your 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 tothis
when configuring your React packages list inside theMainActivity
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 toBuildConfig.DEBUG
to stay synchronized with your build type. When putting CodePush into debug mode, the following behaviors are enabled: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
.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, it's possible to see the expected changes. As soon as this PR is merged, we won't need to do this anymore.
CodePush(String deploymentKey, Context context, boolean isDebugMode, Integer publicKeyResourceDescriptor) - Equivalent to the previous constructor, but allows you to specify the public key resource descriptor needed to read public key content. See the Code Signing section for more details about the Code Signing Feature.
CodePush(String deploymentKey, Context context, boolean isDebugMode, String serverUrl) - Constructor allows you to specify CodePush Server Url. The Default value:
"https://codepush.appcenter.ms/"
is overridden by value specified inserverUrl
.
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 (like
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.