App Center Codepush with React-Native

Fatema Patel 2019-06-29

Objective

CodePush is created by Microsoft, The main idea behind it is that you don't need to update your new release on play store, CodePush automatically updates all the devices in which app is installed With the help of CodePush you can build your project as well as you can test on different devices. Microsoft has made as a requirement that in order to use CodePush has to set up to visual studio app center.

Introduction of Visual Studio App Center

 

Visual Studio App Center is a cloud service to manage life-cycle of our  IOS, Android, Xamarin, react-Native and windows application or open platform and build an API make it easy use and mash to the services you want to use.

The ordinary  UI test of build and Distributed process your app then tested on thousand devices which any of the devices you can see it.

Crash reporting and rich Analytics bring interest and inside the experience of production users.

Visual-studio-app-center works with swift, java, react-native, and even Xamarin.

 

languages

 

So, sign in today and connect your app wit visual-studio-app-center for build function, Automated testing, Distribution, Push notification, rich data Analytics, crash reports.

 

                                          Tools

Here we discuss CodePush of the Distribution function

 

CodePush is created by Microsoft, Microsoft has made as a requirement that in order to use code Push has to set up to visual studio app center.

So to do that go to the Microsoft appcenter.ms and click GET STARTED button by clicking it navigate you to create account tab there it is easy to connect to your favorite repository service so you can build your app. 

Repositories like Azure DevOps, GitHub, Facebook, Google, and BitBucket

 

dashbord

 

click on any repository and it will show you all app of that repository.

As a new user you are not able to see above screenshot for that you need to install appcenter-cli. for that open your terminal go to your root directory and typing

 

npm install -appcenter-cli

Install

note:- if you have any error of access denied try it with sudo command

After completion of the installation, you need to login in the app center by typing 

appcenter login

These gone a use  browser and it gives us a token

token

 Copy that token and paste it into the terminal

login token

Now you are logged in as your user name.

 

Create App

Next, step is to integrate your Android or Ios application to appcenter. 

appcenter apps create -d {YourAppName} -o Android/Ios -p React-Native

Back to the appcenter ho to the home page, you can see your app which you create using above command and click for the app to get started for the CodePush go to Distribution tab and click Codepush option so there you can create a standard deployment to your app.

 

Configure CodePush in app

  • To Getting Started with Code push install  below npm package
npm install --save react-native-code-push
  • Link react-native-code-push
react-native link react-native-code-push

Add AppSerect in the platforms

  • Android

Edit the "{YourAppName}/ android/app/src/main/assets/appcenter-config.json" and replace the  YOUR_APP_SECRET  placeholder value with your App Center project's application secret.

{
    "app_secret": "APP_SECRET"
}
  • IOS

Edit the project's "ios/{YourAppName}/AppCenter-Config.plist" file, and replace the YOUR_APP_SECRET placeholder value with your App Center project's application secret. If AppCenter-Config.plist already exists but not part of your Xcode project, you must add it to the Xcode project manually (right-click the app in XCode and click Add files to ...).

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "https://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
    <dict>
    <key>AppSecret</key>
    <string>{APP_SECRET_VALUE}</string>
    </dict>
</plist>

as we have completed android and ios configuration its time to execute JavaScript portion, compared to both android and ios section the JavaScript phase is bit easy 

Open the react-native project, navigate to your react root component /App.js

  • Write these code

 

import React, { Component } from 'react'
import { StyleSheet, Text, View } from 'react-native'

import CodePush from 'react-native-code-push'

class App extends Component {
  constructor() {
    super()
    this.state = { syncMessage: '' }
  }

  componentDidMount() {
    this.sync()
  }

  codePushStatusDidChange(syncStatus) {
    console.log(syncStatus)
    switch (syncStatus) {
      case CodePush.SyncStatus.CHECKING_FOR_UPDATE:
        this.setState({ syncMessage: 'Checking for update.' })
        break

      case CodePush.SyncStatus.DOWNLOADING_PACKAGE:
        this.setState({ syncMessage: 'Downloading package.' })
        break

      case CodePush.SyncStatus.AWAITING_USER_ACTION:
        this.setState({ syncMessage: 'Awaiting user action.' })
        break

      case CodePush.SyncStatus.INSTALLING_UPDATE:
        this.setState({ syncMessage: 'Installing update.' })
        break

      case CodePush.SyncStatus.UP_TO_DATE:
        this.setState({ syncMessage: 'App is updated.' })
        break

      case CodePush.SyncStatus.UPDATE_IGNORED:
        this.setState({
          syncMessage: 'Update cancelled by user.',
          progress: false
        })
        break

      case CodePush.SyncStatus.UPDATE_INSTALLED:
        this.setState({
          syncMessage: 'Update installed and will be applied on restart.',
          progress: false
        })
        break

      case CodePush.SyncStatus.UNKNOWN_ERROR:
        this.setState({
          syncMessage: 'An unknown error occurred.',

          progress: false
        })

        break
    }
  } /** Update pops a confirmation dialog, and then immediately reboots the app */

  async sync() {
    CodePush.sync(
      { installMode: CodePush.InstallMode.IMMEDIATE, updateDialog: true },

      this.codePushStatusDidChange()
    )

    CodePush.allowRestart()
  }

  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>CodePush is added ^_^</Text>    
        <Text>Hello world </Text>      
        <Text style={styles.messages}>{this.state.syncMessage}</Text>  
      </View>
    )
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
    paddingTop: 50
  },

  messages: {
    marginTop: 30,
    textAlign: 'center'
  },

  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 20
  }
})

/**
* Configured with a MANUAL check frequency for easy testing. For production apps, it is recommended to configure a
* different check frequency, such as ON_APP_START, for a 'hands-off' approach where CodePush.sync() does not
* need to be explicitly called. All options of CodePush.sync() are also available in this decorator.
*/

let codePushOptions = { checkFrequency: CodePush.CheckFrequency.MANUAL }
App = CodePush(codePushOptions)(App)

export default App

 

Add CodePush deployment key

  • Android

At the top right-hand corner of the CodePush page, click on the gadget icon and copy production key,

Edit the {YourAppName}/android/app/main/java/com/main/MainApplication.java  with the following content and replace {PRODUCTION_KEY} with your app PRODUCTION KEY value.

protected List<ReactPackage> getPackages() {

  return Arrays.<ReactPackage>asList(

    ...

    new CodePush("PRODUCTION_KEY", getApplicationContext(),    BuildConfig.DEBUG)

    ...

  )

}

  • IOS

Edit the{YourAppName}/ info.plist of your project with the following content and replace {PRODUCTION_KEY}  with your app PRODUCTION KEY value

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "https://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
    <dict>
    <key>CodePushDeploymentKey</key>
	<string>{PRODUCTION_KEY} </string>
    </dict>
</plist>

Generate release apk and install the app on the device

  1. Generate my-upload-key.keystore and past under /Android/app folder, update gradle.properties and app build.gradle.
  2. Go to the root folder of the app.
  3. Generate app-release.apk: cd android && gradlew assembleRelease
  4. react-native run-android --variant=release

 

Test the CodePush

        1. Check current CodePush status

 appcenter codepush deployment list -a <user-name>/myApp

      You should see a device installed the app.

status                                                                        AppCenter display app status

         2. Make some changes in react native app. Also, you can change the "App version" by changing the version Name from build.grandle (app).

         3. Push the changes to CodePush using this command

appcenter codepush release-react -a <user-name>/testApp -d Production

         4. Reopen the app on the device, you shall see the update warning.

 

Summary

CodePush is a Microsoft solution that allows the developer to update the JavaScript portion of the app instantly without the need of formatted app deployment,CodePush is a faster way to update your app on any mobile platform,CodePush support React-native and Cordova platform, Apple allows this as long as you do not dynamically change the way your app function.

Created on : 2019-06-26
Written by

Fatema Patel

Jr. React Native Developer

Tags
CodePush
react-native-code-push
appcenter-cli