### Install Project Dependencies Source: https://github.com/revopush/react-native-code-push/blob/master/CONTRIBUTING.md Run this command in the project root to install development dependencies. ```bash npm install ``` -------------------------------- ### Install CocoaPods Dependencies Source: https://github.com/revopush/react-native-code-push/blob/master/docs/setup-ios.md Run this command in the ios directory to install necessary CocoaPods dependencies. ```bash cd ios && pod install && cd .. ``` -------------------------------- ### Active Sync with Dialog and Immediate Install Source: https://context7.com/revopush/react-native-code-push/llms.txt Uses codePush.sync to prompt the user with a dialog for updates and installs them immediately upon confirmation. Requires `updateDialog: true` and `installMode: codePush.InstallMode.IMMEDIATE`. ```javascript codePush.sync({ updateDialog: true, installMode: codePush.InstallMode.IMMEDIATE, }); ``` -------------------------------- ### Install @revopush/react-native-code-push Source: https://context7.com/revopush/react-native-code-push/llms.txt Install the package using npm and run iOS pod install. Ensure you are in the project root before running these commands. ```bash npm install --save @revopush/react-native-code-push cd ios && pod install && cd .. ``` -------------------------------- ### Install CodePush CLI Source: https://github.com/revopush/react-native-code-push/blob/master/README.md Install the CodePush CLI globally using npm. Ensure you are logged into Revopush before releasing updates. ```shell npm install -g @revopush/code-push-cli ``` -------------------------------- ### Base64 Encoding and Decoding Example Source: https://github.com/revopush/react-native-code-push/blob/master/ios/CodePush/Base64/README.md Include the header file and use the provided NSData or NSString additions for Base64 encoding and decoding. This example demonstrates encoding a string to Base64 and then decoding it back. ```Objective-C #import "MF_Base64Additions.h" NSString *helloWorld = @"Hello World"; NSString *helloInBase64 = [helloWorld base64String]; NSString *helloDecoded = [NSString stringFromBase64String:helloInBase64]; ``` -------------------------------- ### Install Local Plugin in React Native Project Source: https://github.com/revopush/react-native-code-push/blob/master/CONTRIBUTING.md After cloning the repository and installing dependencies, use this command to link your local clone of the repo into your React Native project. ```bash npm install local_path_to_your_clone_of_this_repo ``` -------------------------------- ### Install React Native CLI Globally Source: https://github.com/revopush/react-native-code-push/blob/master/CONTRIBUTING.md Ensure the React Native command-line interface is installed globally for testing purposes. ```bash npm install -g react-native ``` -------------------------------- ### Android Native Setup: MainApplication.kt Source: https://context7.com/revopush/react-native-code-push/llms.txt Override the JS bundle file resolver in MainApplication.kt to use CodePush.getJSBundleFile(). This ensures the correct bundle is loaded. ```kotlin import com.microsoft.codepush.react.CodePush class MainApplication : Application(), ReactApplication { override val reactNativeHost: ReactNativeHost = object : DefaultReactNativeHost(this) { override fun getPackages(): List = PackageList(this).packages override fun getJSBundleFile(): String { return CodePush.getJSBundleFile() } } } ``` -------------------------------- ### LocalPackage.install Source: https://context7.com/revopush/react-native-code-push/llms.txt Installs a downloaded update at the specified timing. This method is called on the `LocalPackage` object returned by `RemotePackage.download()`. ```APIDOC ## `LocalPackage.install` ### Description Installs a downloaded update at the specified timing. Called on the `LocalPackage` object returned by `RemotePackage.download()`. ### Install Modes - `IMMEDIATE`: Restarts the app immediately. - `ON_NEXT_RESTART`: Applies the update on the next natural app restart. - `ON_NEXT_RESUME`: Applies the update when the app returns from the background. - `ON_NEXT_SUSPEND`: Applies the update while the app is in the background after a specified minimum duration. ### Usage Example ```javascript import codePush from '@revopush/react-native-code-push'; codePush.checkForUpdate().then((remotePackage) => { if (!remotePackage) return; remotePackage.download(({ receivedBytes, totalBytes }) => { console.log(`Downloading: ${Math.round((receivedBytes / totalBytes) * 100)}%`); }).then((localPackage) => { return localPackage.install( codePush.InstallMode.ON_NEXT_RESUME, 120 // minimum 120 seconds in background before applying ); }).then(() => { console.log('Update queued for next resume.'); codePush.notifyAppReady(); // must call when managing manually }); }); ``` ``` -------------------------------- ### iOS Native Setup: Info.plist Source: https://context7.com/revopush/react-native-code-push/llms.txt Configure Info.plist with your iOS deployment key and optionally a public key for bundle code signing verification. Replace YOUR_IOS_DEPLOYMENT_KEY with your actual key. ```xml CodePushDeploymentKey YOUR_IOS_DEPLOYMENT_KEY CodePushPublicKey -----BEGIN PUBLIC KEY----- MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBANkWYydPuyOumR/sn2agNBVDnzyRpM16NAUpYPGxNgjS Ep0etkDNgzzdzyvyl+OsAGBYF3jCxYOXozum+uV5hQECAwEAAQ== -----END PUBLIC KEY----- ``` -------------------------------- ### Logging Sync Process with Event Hooks Source: https://github.com/revopush/react-native-code-push/blob/master/docs/api-js.md This example demonstrates how to use `codePushStatusDidChange` and `codePushDownloadDidProgress` event hooks to log the sync process stages or display a progress bar. ```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); export default MyApp; ``` -------------------------------- ### LocalPackage Source: https://github.com/revopush/react-native-code-push/blob/master/docs/api-js.md Represents a downloaded update that is either already running or has been installed and is pending an app restart. It contains details about the update and methods to install it. ```APIDOC ## 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__: (String) The app binary version that this update is dependent on. - __deploymentKey__: (String) The deployment key that was used to originally download this update. - __description__: (String) The description of the update. - __failedInstall__: (Boolean) Indicates whether this update has been previously installed but was rolled back. - __isFirstRun__: (Boolean) Indicates whether this is the first time the update has been run after being installed. - __isMandatory__: (Boolean) Indicates whether the update is considered mandatory. - __isPending__: (Boolean) Indicates whether this update is in a "pending" state. - __label__: (String) The internal label automatically given to the update by the CodePush server. - __packageHash__: (String) The SHA hash value of the update. - __packageSize__: (Number) The size of the code contained within the update, in bytes. ### Methods - __install(installMode: codePush.InstallMode = codePush.InstallMode.ON_NEXT_RESTART, minimumBackgroundDuration = 0): Promise__ 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. ``` -------------------------------- ### Android Native Setup: build.gradle Source: https://context7.com/revopush/react-native-code-push/llms.txt Apply the CodePush Gradle task at the bottom of your android/app/build.gradle file to integrate CodePush functionality. ```groovy // At the bottom of android/app/build.gradle apply from: "../../node_modules/@revopush/react-native-code-push/android/codepush.gradle" ``` -------------------------------- ### Android Native Setup: strings.xml Source: https://context7.com/revopush/react-native-code-push/llms.txt Configure Android strings.xml with your deployment key, optional server URL, and public key for code signing verification. Replace placeholders with your actual values. ```xml MyApp YOUR_ANDROID_DEPLOYMENT_KEY https://api.revopush.org -----BEGIN PUBLIC KEY----- MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAtPSR9lkGzZ4FR0lxF+ZAP6jJ8+Xi5L60 1BPN4QESoRVSrJM08roOCVrs4qoYqYJy3Of2cQWvNBEh8ti3FhHutiuLFpNdfzM4DjAw0Ti5hOTf TixqVBXTJPYpSjDh7K6tUvp9MV0l5q/Ps3se1vudM1/X6g54lIX/QoEXTdMgR+SKXvlUIC13T7Gk DHT6Z4RlwxkWkOmf2tGguRcEBL6jww7w/3g0kWILz7nNPtXyDhIB9WLH7MKSJWdVCZm+cAqabUfp CFo7sHiyHLnUxcVYOTw3sz9ceaci7z2r8SZdsfjyjiDJrq69eWtvKVUpredy9HtyALtNuLjDITahd h8AzwIDAQAB -----END PUBLIC KEY----- ``` -------------------------------- ### Full Callback Example for codePush.sync() Source: https://context7.com/revopush/react-native-code-push/llms.txt Demonstrates comprehensive usage of `codePush.sync` with custom options, status change callbacks, download progress reporting, and binary mismatch handling. Returns a Promise that resolves with the final sync status. ```javascript codePush.sync( { deploymentKey: 'OVERRIDE_KEY', // override key from native config installMode: codePush.InstallMode.ON_NEXT_RESUME, mandatoryInstallMode: codePush.InstallMode.IMMEDIATE, minimumBackgroundDuration: 300, // 5 minutes updateDialog: { title: 'New Update', optionalUpdateMessage: 'Would you like to install the latest update?', appendReleaseDescription: true, descriptionPrefix: '\n\nRelease notes:\n', }, }, (syncStatus) => { if (syncStatus === codePush.SyncStatus.DOWNLOADING_PACKAGE) { console.log('Download started...'); } else if (syncStatus === codePush.SyncStatus.UPDATE_INSTALLED) { console.log('Update installed successfully.'); } }, ({ receivedBytes, totalBytes }) => { const percent = ((receivedBytes / totalBytes) * 100).toFixed(1); console.log(`Progress: ${percent}%`); }, (binaryMismatchUpdate) => { console.log('A native binary update is available:', binaryMismatchUpdate.appVersion); } ).then((status) => { switch (status) { case codePush.SyncStatus.UP_TO_DATE: console.log('Already up to date.'); break; case codePush.SyncStatus.UPDATE_INSTALLED: console.log('Update installed.'); break; case codePush.SyncStatus.UPDATE_IGNORED: console.log('User dismissed the update.'); break; case codePush.SyncStatus.UNKNOWN_ERROR: console.error('Sync failed with an unknown error.'); break; } }); ``` -------------------------------- ### CodePush Configuration Examples Source: https://github.com/revopush/react-native-code-push/blob/master/docs/api-js.md Illustrates various ways to configure the `codePush` function or decorator to customize update behavior, such as silent updates, app resume sync, and interactive prompts. ```APIDOC ## CodePush Configuration Examples ### 1. Silent Sync on App Start (Default) Automatically downloads and applies updates on the next app restart without user interruption. ```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); export default MyApp; ``` ### 2. Silent Sync Every Time the App Resumes Checks for and applies updates whenever the app returns to the foreground. ```javascript // 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); export default MyApp; ``` ### 3. Interactive Update Prompts the user for permission before downloading and immediately applying updates. Mandatory updates will still notify the user but cannot be ignored. ```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); export default MyApp; ``` ### 4. Log/Display Progress Utilizes event hooks (`codePushStatusDidChange`, `codePushDownloadDidProgress`) to track sync process stages or display progress 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); export default MyApp; ``` ``` -------------------------------- ### Install React Native CodePush Source: https://github.com/revopush/react-native-code-push/blob/master/README.md Install the CodePush package using npm. This is the initial step for integrating CodePush into your React Native project. ```shell npm install --save @revopush/react-native-code-push ``` -------------------------------- ### codePush.sync Source: https://github.com/revopush/react-native-code-push/blob/master/docs/api-js.md Synchronizes the application with the CodePush server, downloading and installing updates based on the provided options and callbacks. ```APIDOC ## codePush.sync ### Description Synchronizes the application with the CodePush server. This method can be configured to perform silent updates, prompt the user for mandatory updates, or provide detailed progress information. ### Method `codePush.sync(syncOptions, syncStatusChangedCallback, downloadProgressCallback, handleBinaryVersionMismatchCallback)` ### Parameters #### Sync Options (`syncOptions`) An object that allows customization of the update behavior. It accepts the same options as `CodePushOptions` with the exception of `checkFrequency`. - **deploymentKey** (String) - Optional. Specifies a deployment key to use for this sync operation, overriding the one configured in the app's Info.plist. - **installMode** (codePush.InstallMode) - Optional. Determines when an update should be installed. Possible values include `codePush.InstallMode.IMMEDIATE`, `codePush.InstallMode.ON_NEXT_RESTART`, `codePush.InstallMode.ON_NEXT_RESUME`. - **mandatoryInstallMode** (codePush.InstallMode) - Optional. Determines when a mandatory update should be installed. Possible values are the same as `installMode`. - **minimumBackgroundDuration** (Number) - Optional. The minimum duration in seconds the app must be in the background before a mandatory update is installed. - **updateDialog** (UpdateDialogOptions) - Optional. Configuration for the update dialog displayed to the user. Can be `true` to show the default dialog, or an object with properties like `appendReleaseDescription`, `descriptionPrefix`, and `title`. #### Callbacks - **syncStatusChangedCallback** ((syncStatus: Number) => void) - Optional. Called when the sync process changes stages. Receives a `SyncStatus` code. - **downloadProgressCallback** ((progress: DownloadProgress) => void) - Optional. Called periodically during update download. Receives a `DownloadProgress` object with `receivedBytes` and `totalBytes`. - **handleBinaryVersionMismatchCallback** ((update: RemotePackage) => void) - Optional. Called when a binary update is available. ### Return Value A `Promise` that resolves to a `SyncStatus` code indicating the outcome of the sync operation. ### SyncStatus Values - **codePush.SyncStatus.UP_TO_DATE** (0) - The app is up-to-date. - **codePush.SyncStatus.UPDATE_INSTALLED** (1) - An update was installed. - **codePush.SyncStatus.UPDATE_IGNORED** (2) - An optional update was ignored by the user. - **codePush.SyncStatus.SYNC_IN_PROGRESS** (4) - A sync operation is already in progress. ### Example Usage ```javascript // Example 1: Using a specific deployment key codePush.sync({ deploymentKey: "YOUR_DEPLOYMENT_KEY" }); // Example 2: Silent download and install on next resume after 5 minutes in background codePush.sync({ installMode: codePush.InstallMode.ON_NEXT_RESUME, minimumBackgroundDuration: 60 * 5 }); // Example 3: Customizing the update dialog title codePush.sync({ updateDialog: { title: "New version available!" } }); // Example 4: Handling sync status and download progress codePush.sync( { updateDialog: true }, (status) => { switch (status) { case codePush.SyncStatus.DOWNLOADING_PACKAGE: console.log("Downloading update..."); break; case codePush.SyncStatus.INSTALLING_UPDATE: console.log("Installing update..."); break; } }, ({ receivedBytes, totalBytes }) => { const progress = receivedBytes / totalBytes * 100; console.log(`Download progress: ${progress.toFixed(2)}%`); } ); ``` ``` -------------------------------- ### Install Downloaded CodePush Update Source: https://context7.com/revopush/react-native-code-push/llms.txt Installs a downloaded update at a specified timing. This is called on the LocalPackage object returned by RemotePackage.download(). Ensure codePush.notifyAppReady() is called when managing updates manually. ```javascript import codePush from '@revopush/react-native-code-push'; codePush.checkForUpdate().then((remotePackage) => { if (!remotePackage) return; remotePackage.download(({ receivedBytes, totalBytes }) => { console.log(`Downloading: ${Math.round((receivedBytes / totalBytes) * 100)}%`); }).then((localPackage) => { // Install modes: // IMMEDIATE — restart app right now // ON_NEXT_RESTART — apply on next natural restart (default) // ON_NEXT_RESUME — apply when app comes back from background // ON_NEXT_SUSPEND — apply while in background after minimumBackgroundDuration seconds return localPackage.install( codePush.InstallMode.ON_NEXT_RESUME, 120 // minimum 120 seconds in background before applying ); }).then(() => { console.log('Update queued for next resume.'); codePush.notifyAppReady(); // must call when managing manually }); }); ``` -------------------------------- ### Customize Sync Options Source: https://github.com/revopush/react-native-code-push/blob/master/docs/api-js.md Use the sync method with an options object to customize update behavior. This allows for specifying a different deployment key, controlling install modes, and configuring update dialogs. ```javascript // Use a different deployment key for this // specific call, instead of the one configured // in the Info.plist file codePush.sync({ deploymentKey: "KEY" }); ``` ```javascript // 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 }); ``` ```javascript // 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 }); ``` ```javascript // Changing the title displayed in the // confirmation dialog of an "active" update codePush.sync({ updateDialog: { title: "An update is available!" } }); ``` ```javascript // 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 }); ``` -------------------------------- ### sync Source: https://github.com/revopush/react-native-code-push/blob/master/docs/api-js.md A comprehensive method that checks for an update, downloads it, and installs it in a single call. Recommended for most use cases unless custom UI or behavior is required. ```APIDOC ## sync ### Description 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 ### Method `CodePush.sync()` ``` -------------------------------- ### codePush.sync Source: https://context7.com/revopush/react-native-code-push/llms.txt Checks for an update, downloads it, and installs it in a single call. Supports silent and active (dialog-prompted) modes. Returns a Promise. ```APIDOC ## `codePush.sync` Checks for an update, downloads it, and installs it in a single call. Supports silent and active (dialog-prompted) modes. Returns a `Promise`. ```javascript import codePush from '@revopush/react-native-code-push'; // Fully silent: download and install on next restart codePush.sync(); // Active mode: show dialog, install immediately on confirmation codePush.sync({ updateDialog: true, installMode: codePush.InstallMode.IMMEDIATE, }); // With all callbacks: status changes, download progress, binary mismatch codePush.sync( { deploymentKey: 'OVERRIDE_KEY', // override key from native config installMode: codePush.InstallMode.ON_NEXT_RESUME, mandatoryInstallMode: codePush.InstallMode.IMMEDIATE, minimumBackgroundDuration: 300, // 5 minutes updateDialog: { title: 'New Update', optionalUpdateMessage: 'Would you like to install the latest update?', appendReleaseDescription: true, descriptionPrefix: '\n\nRelease notes:\n', }, }, (syncStatus) => { if (syncStatus === codePush.SyncStatus.DOWNLOADING_PACKAGE) { console.log('Download started...'); } else if (syncStatus === codePush.SyncStatus.UPDATE_INSTALLED) { console.log('Update installed successfully.'); } }, ({ receivedBytes, totalBytes }) => { const percent = ((receivedBytes / totalBytes) * 100).toFixed(1); console.log(`Progress: ${percent}%`); }, (binaryMismatchUpdate) => { console.log('A native binary update is available:', binaryMismatchUpdate.appVersion); } ).then((status) => { switch (status) { case codePush.SyncStatus.UP_TO_DATE: console.log('Already up to date.'); break; case codePush.SyncStatus.UPDATE_INSTALLED: console.log('Update installed.'); break; case codePush.SyncStatus.UPDATE_IGNORED: console.log('User dismissed the update.'); break; case codePush.SyncStatus.UNKNOWN_ERROR: console.error('Sync failed with an unknown error.'); break; } }); ``` ``` -------------------------------- ### Interactive Update Prompt with CodePush HOC Source: https://context7.com/revopush/react-native-code-push/llms.txt Enables an interactive update process where the user is prompted to install the update immediately. Requires custom dialog text and immediate installation mode. ```javascript class MyApp3 extends Component { render() { return null; } } export default codePush({ updateDialog: { title: 'Update Available', optionalUpdateMessage: 'A new version is ready. Install now?', optionalInstallButtonLabel: 'Install', optionalIgnoreButtonLabel: 'Later', appendReleaseDescription: true, descriptionPrefix: '\n\nChanges:\n', }, installMode: codePush.InstallMode.IMMEDIATE, mandatoryInstallMode: codePush.InstallMode.IMMEDIATE, })(MyApp3); ``` -------------------------------- ### getCurrentPackage Source: https://github.com/revopush/react-native-code-push/blob/master/docs/api-js.md Retrieves metadata about the currently installed CodePush update. Note: This method is deprecated in favor of `getUpdateMetadata`. ```APIDOC ## getCurrentPackage ### Description Retrieves the metadata about the currently installed update (like description, installation time, size). *NOTE: As of `v1.10.3-beta` of the CodePush module, this method is deprecated in favor of [`getUpdateMetadata`](#codepushgetupdatemetadata)*. ### Method `CodePush.getCurrentPackage()` ``` -------------------------------- ### Silent Sync on App Start Source: https://github.com/revopush/react-native-code-push/blob/master/docs/api-js.md This configuration provides a fully silent update experience. Updates are downloaded and applied on the next app restart without user interruption. ```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); export default MyApp; ``` -------------------------------- ### iOS Native Setup: AppDelegate.swift Source: https://context7.com/revopush/react-native-code-push/llms.txt Configure Swift AppDelegate to load the CodePush-managed JS bundle in release builds. This replaces the default static bundle loading. ```swift import CodePush override func bundleURL() -> URL? { #if DEBUG RCTBundleURLProvider.sharedSettings().jsBundleURL(forBundleRoot: "index") #else CodePush.bundleURL() #endif } ``` -------------------------------- ### iOS Native Setup: AppDelegate.m Source: https://context7.com/revopush/react-native-code-push/llms.txt Configure Objective-C AppDelegate to load the CodePush-managed JS bundle in release builds. This replaces the default static bundle loading. ```objective-c #import // In your AppDelegate: - (NSURL *)sourceURLForBridge:(RCTBridge *)bridge { #if DEBUG return [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index"]; #else return [CodePush bundleURL]; #endif } ``` -------------------------------- ### Silent Sync with codePush.sync() Source: https://context7.com/revopush/react-native-code-push/llms.txt Initiates a silent update check, download, and installation. The update is applied on the next app restart. This is the simplest way to use codePush.sync. ```javascript import codePush from '@revopush/react-native-code-push'; // Fully silent: download and install on next restart codePush.sync(); ``` -------------------------------- ### Restart App Source: https://github.com/revopush/react-native-code-push/blob/master/docs/api-js.md Immediately restarts the application. If `onlyIfUpdateIsPending` is true, the restart only occurs if there's a pending update. Useful for applying updates with `ON_NEXT_RESTART` or `ON_NEXT_RESUME` install modes in specific user-driven scenarios. ```javascript codePush.restartApp(onlyIfUpdateIsPending: Boolean = false): void; ``` -------------------------------- ### codePush.sync Source: https://github.com/revopush/react-native-code-push/blob/master/docs/api-js.md Synchronizes your app's JavaScript bundle and image assets with the latest release to the configured deployment. This method handles the update check, download, and installation experience automatically. It supports both silent and active update modes. ```APIDOC ## codePush.sync ### Description Synchronizes your app's JavaScript bundle and image assets with the latest release to the configured deployment. Unlike `checkForUpdate`, `sync` handles the entire update process: checking for updates, downloading them, and applying them. It supports two main modes: 1. **Silent mode (default):** Automatically downloads and applies updates on the next app restart without user interruption. 2. **Active mode:** Prompts the user before downloading and immediately applies the update. Mandatory updates will still notify the user but won't offer a choice to ignore. ### Method Signature ```javascript codePush.sync(options?: Object, syncStatusChangeCallback?: function(syncStatus: Number), downloadProgressCallback?: function(progress: DownloadProgress), handleBinaryVersionMismatchCallback?: function(update: RemotePackage)): Promise; ``` ### Parameters * **options** (Object) - Optional. Configuration options for the sync process. See [Sync Options](https://github.com/microsoft/react-native-code-push/blob/master/docs/api-js.md#syncoptions) for details. * **syncStatusChangeCallback** (function) - Optional. A callback function that is invoked when the sync status changes. It receives a `syncStatus` number. * **downloadProgressCallback** (function) - Optional. A callback function that is invoked periodically to report download progress. It receives a `progress` object of type `DownloadProgress`. * **handleBinaryVersionMismatchCallback** (function) - Optional. A callback function invoked when a binary version mismatch occurs. It receives an `update` object of type `RemotePackage`. ### Request Example ```javascript // Fully silent update codePush.sync(); // Active update with immediate installation codePush.sync({ updateDialog: true, installMode: codePush.InstallMode.IMMEDIATE }); ``` ### Response * **Promise** - A promise that resolves with a number indicating the sync status. ``` -------------------------------- ### Get Update Metadata Source: https://github.com/revopush/react-native-code-push/blob/master/docs/api-js.md Retrieves metadata for an installed CodePush update. Useful for displaying 'what's new' dialogs or checking for pending updates. It resolves to a LocalPackage instance or null if no update matches the specified state. ```javascript codePush.getUpdateMetadata(updateState: UpdateState = UpdateState.RUNNING): Promise; ``` ```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 }); } }); ``` ```javascript // 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? } }); ``` -------------------------------- ### Notify App Ready Source: https://github.com/revopush/react-native-code-push/blob/master/docs/api-js.md Notifies the CodePush runtime that a freshly installed update is successful, preventing an automatic rollback on the next restart. This must be called within the updated bundle's code. If using `sync` on app start, this is called automatically. ```javascript codePush.notifyAppReady(): Promise; ``` -------------------------------- ### Build Staging and Production IPAs Source: https://context7.com/revopush/react-native-code-push/llms.txt Use xcodebuild commands to create distinct IPA files for staging and production environments by specifying the build configuration. This is typically followed by releasing to the corresponding Revopush deployment. ```bash # Build staging IPA xcodebuild -configuration Staging -scheme MyApp archive # Build production IPA xcodebuild -configuration Release -scheme MyApp archive ``` -------------------------------- ### Run All Unit Tests on Android and iOS Without Building Source: https://github.com/revopush/react-native-code-push/blob/master/CONTRIBUTING.md Execute all unit tests on both platforms without performing a build step first. Use the ':fast' suffix. ```bash npm run test:fast ``` -------------------------------- ### Run All Unit Tests on Android and iOS Source: https://github.com/revopush/react-native-code-push/blob/master/CONTRIBUTING.md This command executes the full unit test suite for both Android and iOS platforms. ```bash npm run test ``` -------------------------------- ### codePush.getCurrentPackage Source: https://github.com/revopush/react-native-code-push/blob/master/docs/api-js.md Retrieves the metadata about the currently installed CodePush package. Deprecated in favor of codePush.getUpdateMetadata. ```APIDOC ## codePush.getCurrentPackage ### Description Retrieves the metadata about the currently installed CodePush package. This method is considered deprecated as of `v1.10.3-beta` and `codePush.getUpdateMetadata` is recommended instead. ### Method `codePush.getCurrentPackage(): Promise;` ### Parameters None ### Response #### Success Response - `null`: If the app is currently running the JS bundle from the binary and not a CodePush update. - `LocalPackage`: An instance representing the metadata for the currently running CodePush update. ### Response Example ```javascript codePush.getCurrentPackage() .then((update) => { if (update && update.isFirstRun && update.description) { // Display a "what's new?" modal } }); ``` ``` -------------------------------- ### getUpdateMetadata Source: https://github.com/revopush/react-native-code-push/blob/master/docs/api-js.md Retrieves metadata for an installed CodePush update, such as its description and whether it's mandatory. ```APIDOC ## getUpdateMetadata ### Description Retrieves the metadata for an installed update (like description, mandatory). ### Method `CodePush.getUpdateMetadata()` ``` -------------------------------- ### Run All Unit Tests on iOS Source: https://github.com/revopush/react-native-code-push/blob/master/CONTRIBUTING.md Execute the complete unit test suite specifically for the iOS platform. ```bash npm run test:ios ``` -------------------------------- ### Run All Unit Tests on iOS and Restart Emulators Source: https://github.com/revopush/react-native-code-push/blob/master/CONTRIBUTING.md Execute all unit tests on iOS, ensuring emulators are restarted (and killed if running). Set the CLEAN=true environment variable. ```bash CLEAN=true npm run test:ios ``` -------------------------------- ### codePush.disallowRestart Source: https://github.com/revopush/react-native-code-push/blob/master/docs/api-js.md Temporarily disallows programmatic restarts to occur as a result of update installations or direct calls to restartApp. Restarts are queued until allowRestart() is called. ```APIDOC ## codePush.disallowRestart ### Description Temporarily disallows programmatic restarts to occur as a result of update installations or direct calls to restartApp. Restarts are queued until allowRestart() is called. ### Method `codePush.disallowRestart(): void;` ### Parameters None ### Request Example ```javascript codePush.disallowRestart(); ``` ### Response None ``` -------------------------------- ### Load Keys from PEM Files and Sign/Verify JWT Source: https://github.com/revopush/react-native-code-push/blob/master/ios/CodePush/JWT/README.md Demonstrates loading RSA public and private keys from PEM files and using them to sign and verify JWTs. Ensure PEM files are correctly formatted and accessible. ```Objective-C // Load keys - (NSString *)pemKeyStringFromFileWithName:(NSString *)string inBundle:(NSBundle *)bundle { NSURL *fileURL = [bundle URLForResource:name withExtension:@"pem"]; NSError *error = nil; NSString *fileContent = [NSString stringWithContentsOfURL:fileURL encoding:NSUTF8StringEncoding error:&error]; if (error) { NSLog(@"%@ error: %@", self.debugDescription, error); return nil; } } // Sign and verify - (void)signAndVerifyWithPrivateKeyPemString:(NSString *)privateKey publicKeyPemString:(NSString *)publicKey privateKeyPassphrase:(NSString *)passphrase { NSString *algorithmName = @"RS256"; id signDataHolder = [JWTAlgorithmRSFamilyDataHolder new].keyExtractorType([JWTCryptoKeyExtractor privateKeyWithPEMBase64].type).privateKeyCertificatePassphrase(passphrase).algorithmName(algorithmName).secret(privateKey); id verifyDataHolder = [JWTAlgorithmRSFamilyDataHolder new].keyExtractorType([JWTCryptoKeyExtractor publicKeyWithPEMBase64].type).algorithmName(algorithmName).secret(publicKey); // sign NSDictionary *payloadDictionary = @{@"hello": @"world"}; JWTCodingBuilder *signBuilder = [JWTEncodingBuilder encodePayload:payloadDictionary].addHolder(signDataHolder); JWTCodingResultType *signResult = signBuilder.result; NSString *token = nil; if (signResult.successResult) { // success NSLog(@"%@ success: %@", self.debugDescription, signResult.successResult.encoded); token = signResult.successResult.encoded; } else { // error NSLog(@"%@ error: %@", self.debugDescription, signResult.errorResult.error); } // verify if (token == nil) { NSLog(@"something wrong"); } JWTCodingBuilder *verifyBuilder = [JWTDecodingBuilder decodeMessage:token].addHolder(verifyDataHolder); JWTCodingResultType *verifyResult = verifyBuilder.result; if (verifyResult.successResult) { // success NSLog(@"%@ success: %@", self.debugDescription, verifyResult.successResult.payload); token = verifyResult.successResult.encoded; } else { // error NSLog(@"%@ error: %@", self.debugDescription, verifyResult.errorResult.error); } } ``` -------------------------------- ### clearUpdates Source: https://github.com/revopush/react-native-code-push/blob/master/docs/api-js.md Clears all downloaded CodePush updates. This is primarily useful when switching to a different deployment that might have an older release than the currently installed package. ```APIDOC ## clearUpdates ### Description Clear all downloaded CodePush updates. This is useful when switching to a different deployment which may have an older release than the current package. _Note: we don’t recommend to use this method in scenarios other than that (CodePush will call this method automatically when needed in other cases) as it could lead to unpredictable behavior._ ### Method `CodePush.clearUpdates()` ``` -------------------------------- ### Run All Unit Tests on Android Source: https://github.com/revopush/react-native-code-push/blob/master/CONTRIBUTING.md Execute the complete unit test suite specifically for the Android platform. ```bash npm run test:android ``` -------------------------------- ### CodePush SyncStatus Enum Source: https://context7.com/revopush/react-native-code-push/llms.txt Represents the status reported to the syncStatusChangedCallback or resolved by the codePush.sync() Promise. Covers various stages from checking for updates to installation. ```typescript // SyncStatus — reported to syncStatusChangedCallback / sync() Promise resolution codePush.SyncStatus.UP_TO_DATE // no update available (0) codePush.SyncStatus.UPDATE_INSTALLED // update downloaded and queued/applied (1) codePush.SyncStatus.UPDATE_IGNORED // user dismissed the optional update dialog (2) codePush.SyncStatus.UNKNOWN_ERROR // sync failed (3) codePush.SyncStatus.SYNC_IN_PROGRESS // another sync is already running (4) codePush.SyncStatus.CHECKING_FOR_UPDATE // querying server (5) codePush.SyncStatus.AWAITING_USER_ACTION // dialog shown, waiting for user (6) codePush.SyncStatus.DOWNLOADING_PACKAGE // downloading the update bundle (7) codePush.SyncStatus.INSTALLING_UPDATE // update downloaded, installing (8) ``` -------------------------------- ### codePush.clearUpdates Source: https://context7.com/revopush/react-native-code-push/llms.txt Clears all locally downloaded CodePush updates from device storage. This is useful when switching to a deployment with an older release than the currently installed update. ```APIDOC ## `codePush.clearUpdates` ### Description Clears all locally downloaded CodePush updates from device storage. Primarily useful when switching to a deployment that contains an older release than the currently installed update. ### Usage Example ```javascript import codePush from '@revopush/react-native-code-push'; // Switching deployments: clear old updates before syncing with the new key async function switchToStagingDeployment(stagingKey) { codePush.clearUpdates(); await codePush.sync({ deploymentKey: stagingKey }); } ``` ``` -------------------------------- ### Run Core Unit Tests on Android from NPM Source: https://github.com/revopush/react-native-code-push/blob/master/CONTRIBUTING.md Execute core unit tests on Android, pulling the plugin from NPM. Set both NPM=true and CORE=true environment variables. ```bash NPM=true CORE=true npm run test:android ``` -------------------------------- ### CodePush CheckFrequency Enum Source: https://context7.com/revopush/react-native-code-push/llms.txt Specifies when the CodePush Higher-Order Component (HOC) should trigger a synchronization check for updates. Defaults to checking on app start. ```typescript // CheckFrequency — when the HOC triggers sync codePush.CheckFrequency.ON_APP_START // when root component mounts (0, default) codePush.CheckFrequency.ON_APP_RESUME // when app comes back to foreground (1) codePush.CheckFrequency.MANUAL // only when codePush.sync() is called explicitly (2) ``` -------------------------------- ### Run All Unit Tests on iOS from NPM Source: https://github.com/revopush/react-native-code-push/blob/master/CONTRIBUTING.md Execute all unit tests on iOS, pulling the plugin from NPM instead of the local version. Set the NPM=true environment variable. ```bash NPM=true npm run test:ios ``` -------------------------------- ### Configure Bundle URL Method (Swift) Source: https://github.com/revopush/react-native-code-push/blob/master/docs/setup-ios.md Dynamically switch between the packager server and CodePush using the DEBUG macro in your AppDelegate.swift's bundleURL method. ```swift override func bundleURL() -> URL? { #if DEBUG RCTBundleURLProvider.sharedSettings().jsBundleURL(forBundleRoot: "index") #else CodePush.bundleURL() #endif } ``` -------------------------------- ### Basic Release Command Source: https://github.com/revopush/react-native-code-push/blob/master/README.md Release updates for your application by specifying the app name and platform. This command uses sensible defaults for bundling and entry files. ```shell revopush release-react ``` ```shell revopush release-react MyApp android -d Production ``` ```shell release-react MyApp ios ``` -------------------------------- ### codePush.notifyAppReady Source: https://context7.com/revopush/react-native-code-push/llms.txt Signals to the CodePush runtime that the current update has launched successfully, preventing an automatic rollback. This must be called when manually managing update installs. ```APIDOC ## `codePush.notifyAppReady` Signals to the CodePush runtime that the current update has launched successfully, preventing an automatic rollback. **Must be called** when manually managing update installs (i.e., not using `sync()`). ```javascript import codePush from '@revopush/react-native-code-push'; import { useEffect } from 'react'; function App() { useEffect(() => { // Manually check and install codePush.checkForUpdate().then((update) => { if (update) { return update.download().then((pkg) => pkg.install(codePush.InstallMode.ON_NEXT_RESTART) ); } }); // Mark the current update as successful to prevent auto-rollback codePush.notifyAppReady().then((report) => { if (report) { console.log(`Deployment status: ${report.status}`); } }); }, []); return null; } ``` ``` -------------------------------- ### Encode and Decode JWT with Algorithm Chain Source: https://github.com/revopush/react-native-code-push/blob/master/ios/CodePush/JWT/README.md Provides an example of encoding claims into a JWT and then decoding it, utilizing algorithm data holders and chains for both operations. ```objective-c JWTClaimsSet *claimsSet = [[JWTClaimsSet alloc] init]; // fill it claimsSet.issuer = @"Facebook"; claimsSet.subject = @"Token"; claimsSet.audience = @"https://jwt.io"; // encode it NSString *secret = @"secret"; NSString *algorithmName = @"HS384"; NSDictionary *headers = @{@"custom":@"value"}; idholder = [JWTAlgorithmHSFamilyDataHolder new].algorithmName(algorithmName).secret(secret); JWTCodingResultType *result = [JWTEncodingBuilder encodeClaimsSet:claimsSet].headers(headers).addHolder(holder).result; NSString *encodedToken = result.successResult.encoded; if (result.successResult) { // handle encoded result NSLog(@"encoded result: %@", result.successResult.encoded); } else { // handle error NSLog(@"encode failed, error: %@", result.errorResult.error); } // decode it // you can set any property that you want, all properties are optional JWTClaimsSet *trustedClaimsSet = [claimsSet copy]; NSNumber *options = @(JWTCodingDecodingOptionsNone); NSString *yourJwt = encodedToken; // from previous example JWTCodingResultType *decodedResult = [JWTDecodingBuilder decodeMessage:yourJwt].claimsSet(claimsSet).addHolder(holder).options(options).and.result; if (decodedResult.successResult) { // handle decoded result NSLog(@"decoded result: %@", decodedResult.successResult.headerAndPayloadDictionary); NSLog(@"headers: %@", decodedResult.successResult.headers); NSLog(@"payload: %@", decodedResult.successResult.payload); } else { // handle error NSLog(@"decode failed, error: %@", decodedResult.errorResult.error); } ``` -------------------------------- ### Configure Info.plist for Deployment Key Source: https://context7.com/revopush/react-native-code-push/llms.txt Reference the Xcode user-defined setting for the CodePush deployment key in your Info.plist file. This allows for dynamic key switching based on build configurations. ```xml CodePushDeploymentKey $(CODEPUSH_KEY) ``` -------------------------------- ### Get CodePush Update Metadata Source: https://context7.com/revopush/react-native-code-push/llms.txt Retrieves metadata for the currently running or pending CodePush update. Useful for displaying update information or triggering restarts. ```javascript import codePush from '@revopush/react-native-code-push'; // Get metadata for the currently RUNNING update codePush.getUpdateMetadata(codePush.UpdateState.RUNNING).then((update) => { if (update) { console.log(`Running update: label=${update.label}, version=${update.appVersion}`); if (update.isFirstRun && update.description) { // Show "What's New" dialog to the user alert(`What's New:\n${update.description}`); } } else { console.log('Running the binary bundle (no CodePush update active).'); } }); ``` ```javascript // Check for a PENDING update (downloaded but awaiting restart) codePush.getUpdateMetadata(codePush.UpdateState.PENDING).then((update) => { if (update) { console.log(`Pending update ready: ${update.label}. Restarting now...`); codePush.restartApp(); } }); ``` ```javascript // Check LATEST (running or pending) codePush.getUpdateMetadata(codePush.UpdateState.LATEST).then((update) => { if (update) { console.log(`Latest installed update: ${update.label}, mandatory=${update.isMandatory}`); } }); ``` -------------------------------- ### Initialize CodePush with Public Key Resource Descriptor Source: https://github.com/revopush/react-native-code-push/blob/master/docs/api-android.md Initializes the CodePush runtime, allowing specification of a public key resource descriptor for reading public key content, enabling the Code Signing feature. ```java new CodePush("deployment-key", context, isDebugMode, R.string.CodePushPublicKey); ``` -------------------------------- ### disallowRestart Source: https://github.com/revopush/react-native-code-push/blob/master/docs/api-js.md Temporarily disallows any programmatic restarts that would occur due to a CodePush update installation. This is useful for preventing interruptions during critical processes like onboarding. ```APIDOC ## disallowRestart ### Description 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 (for example an onboarding process) needs to ensure that no end-user interruptions can occur during its lifetime. ### Method `CodePush.disallowRestart()` ```