Get OTP code from firebase

Please follow the stable version

https://rnfirebase.io/docs/v5.x.x/getting-started

Go to Firebase console

https://console.firebase.google.com/ and add project

IAM_Management_Console

Fill the infomations and create

IAM_Management_Console

Click on iOS icon to get info

IAM_Management_Console

Add firebase to the app

IAM_Management_Console

Enable Phone option

IAM_Management_Console

Download and drag GoogleService-Info.plist to Xcode

IAM_Management_Console

Procced

IAM_Management_Console

PodFile

Install CocoaPod

sudo gem install cocoapods

Init Podfile

cd ios

then

pod init

Open your Podfile and add ( Can delete the things unnecessary)

# Uncomment the next line to define a global platform for your project
platform :ios, '9.0'

target 'FirebaseDetox' do
  # Comment the next line if you don't want to use dynamic frameworks
  use_frameworks!

  # Pods for firebaseApp
  pod 'Firebase/Core'
  pod 'Firebase/Auth'

end

IAM_Management_Console

then run

pod install

Need to continue proceed click next step at Firebase console

Result

IAM_Management_Console

Step

1. Install react-native-firebase

yarn add react-native-firebase

Check package.json make sure verion 5.x.x

react-native link react-native-firebase

Podfile

AppDelegate.m

IAM_Management_Console

#import "AppDelegate.h"

#import <React/RCTBridge.h>
#import <React/RCTBundleURLProvider.h>
#import <React/RCTRootView.h>

@import Firebase;

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
  RCTBridge *bridge = [[RCTBridge alloc] initWithDelegate:self launchOptions:launchOptions];
  RCTRootView *rootView = [[RCTRootView alloc] initWithBridge:bridge
                                                   moduleName:@"FirebaseDetox"
                                            initialProperties:nil];

  rootView.backgroundColor = [[UIColor alloc] initWithRed:1.0f green:1.0f blue:1.0f alpha:1];

  self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
  UIViewController *rootViewController = [UIViewController new];
  rootViewController.view = rootView;
  self.window.rootViewController = rootViewController;
  [self.window makeKeyAndVisible];
  [FIRApp configure];
  return YES;
}

- (NSURL *)sourceURLForBridge:(RCTBridge *)bridge
{
#if DEBUG
  return [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index" fallbackResource:nil];
#else
  return [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"];
#endif
}

@end

Make sure

IAM_Management_Console

Turn on Notification

IAM_Management_Console

From console

IAM_Management_Console

###

IAM_Management_Console

###

IAM_Management_Console

###

IAM_Management_Console

Turn off Recapcha

IAM_Management_Console

Config GoogleService-plist.info

  1. Open GoogleService-Info.plist and Select REVERSED_CLIENT_ID
  2. Open FirebaseDetox.xcworkspace
  3. Double Click on FirebaseDetox
  4. At TARGETS : Select FirebaseDetox
  5. Choose Info Tab
  6. Select URL Type
  7. Paste REVERSED_CLIENT_ID

IAM_Management_Console

###

cd ios

open FirebaseDetox.xcworkspace

If you see any error

Delete Pods folder and re try

rm -rf Pods
rm Podfile.lock
rm -rf FirebaseDetox.xcworkspace

Re install Pod

pod install

pod update

CODE

Update code for App.js

import React, { Component } from 'react'
import { View, Button, Text, TextInput, Image } from 'react-native'

import firebase from 'react-native-firebase'

const successImageUri =
  'https://cdn.pixabay.com/photo/2015/06/09/16/12/icon-803718_1280.png'

export default class PhoneAuthTest extends Component {
  constructor(props) {
    super(props)
    this.unsubscribe = null
    this.state = {
      user: null,
      message: '',
      codeInput: '',
      phoneNumber: '+6582309048',
      confirmResult: null
    }
  }

  componentDidMount() {
    this.unsubscribe = firebase.auth().onAuthStateChanged(user => {
      if (user) {
        this.setState({ user: user.toJSON() })
      } else {
        // User has been signed out, reset the state
        this.setState({
          user: null,
          message: '',
          codeInput: '',
          phoneNumber: '+6582309048',
          confirmResult: null
        })
      }
    })
  }

  componentWillUnmount() {
    if (this.unsubscribe) this.unsubscribe()
  }

  signIn = () => {
    const { phoneNumber } = this.state
    this.setState({ message: 'Sending code ...' })

    firebase
      .auth()
      .signInWithPhoneNumber(phoneNumber)
      .then(confirmResult =>
        this.setState({ confirmResult, message: 'Code has been sent!' })
      )
      .catch(error =>
        this.setState({
          message: `Sign In With Phone Number Error: ${error.message}`
        })
      )
  }

  confirmCode = () => {
    const { codeInput, confirmResult } = this.state

    if (confirmResult && codeInput.length) {
      confirmResult
        .confirm(codeInput)
        .then(user => {
          this.setState({ message: 'Code Confirmed!' })
        })
        .catch(error =>
          this.setState({ message: `Code Confirm Error: ${error.message}` })
        )
    }
  }

  signOut = () => {
    firebase.auth().signOut()
  }

  renderPhoneNumberInput() {
    const { phoneNumber } = this.state

    return (
      <View style=>
        <Text testID="welcome">Enter phone number:</Text>
        <TextInput
          autoFocus
          style=
          onChangeText={value => this.setState({ phoneNumber: value })}
          placeholder={'Phone number ... '}
          value={phoneNumber}
        />
        <Button title="Sign In" color="green" onPress={this.signIn} />
      </View>
    )
  }

  renderMessage() {
    const { message } = this.state

    if (!message.length) return null

    return (
      <Text style=>
        {message}
      </Text>
    )
  }

  renderVerificationCodeInput() {
    const { codeInput } = this.state

    return (
      <View style=>
        <Text>Enter verification code below:</Text>
        <TextInput
          autoFocus
          style=
          onChangeText={value => this.setState({ codeInput: value })}
          placeholder={'Code ... '}
          value={codeInput}
        />
        <Button
          title="Confirm Code"
          color="#841584"
          onPress={this.confirmCode}
        />
      </View>
    )
  }

  render() {
    const { user, confirmResult } = this.state
    return (
      <View style=>
        {!user && !confirmResult && this.renderPhoneNumberInput()}

        {this.renderMessage()}

        {!user && confirmResult && this.renderVerificationCodeInput()}

        {user && (
          <View
            style=
          >
            <Image
              source=
              style=
            />
            <Text style=>Signed In!</Text>
            <Text>{JSON.stringify(user)}</Text>
            <Button title="Sign Out" color="red" onPress={this.signOut} />
          </View>
        )}
      </View>
    )
  }
}

Setup Detox

Follow the link to install Detox

https://github.com/wix/Detox/blob/master/docs/Introduction.GettingStarted.md

npm install detox --save-dev
npm install jest --save-dev

Add Detox config to package.json

We are using Pod so we have build with .xcworkspace file

"xcodebuild -workspace ios/FirebaseDetox.xcworkspace -scheme FirebaseDetox -configuration Debug -sdk iphonesimulator -derivedDataPath ios/build"

NOTE

Check list simulator

xcrun simctl list

Detail

"detox": {
    "configurations": {
      "ios.sim.debug": {
        "binaryPath": "ios/build/Build/Products/Debug-iphonesimulator/FirebaseDetox.app",
        "build": "xcodebuild -workspace ios/FirebaseDetox.xcworkspace -scheme FirebaseDetox -configuration Debug -sdk iphonesimulator -derivedDataPath ios/build",
        "type": "ios.simulator",
        "name": "iPhone 8"
      }
    },
    "test-runner": "jest"
  }

Generate e2e test folder

detox init -r jest

Open firstTest.spec.js and update test case

describe('Example', () => {
  beforeEach(async () => {
    await device.reloadReactNative()
  })

  it('should have welcome screen', async () => {
    await expect(element(by.id('welcome'))).toBeVisible()
  })
})

Open App.js and update

Add renderPhoneNumberInput() function add

renderPhoneNumberInput() {
    const { phoneNumber } = this.state

    return (
      <View style=>
        <Text testID="welcome">Enter phone number:</Text>
        <TextInput
          autoFocus
          style=
          onChangeText={value => this.setState({ phoneNumber: value })}
          placeholder={'Phone number ... '}
          value={phoneNumber}
        />
        <Button title="Sign In" color="green" onPress={this.signIn} />
      </View>
    )
  }

Run

react-native start

react-native run-ios

IAM_Management_Console

If you catch this error

open .xcworkspace and update build system to Legacy Build System

IAM_Management_Console

Open 1 terminal tab run

yarn start -- --reset-cache

detox build

detox test

IAM_Management_Console

Android

1. Add Android

IAM_Management_Console

2. Fill up the form

IAM_Management_Console

Follow this link https://facebook.github.io/react-native/docs/signed-apk-android to generate SHA

/usr/libexec/java_home

you can get the link /Library/Java/JavaVirtualMachines/jdk-XX.X.X.jdk/Contents/Home

assume your link is cd /Library/Java/JavaVirtualMachines/jdk-11.0.2.jdk/Contents/Home

cd /Library/Java/JavaVirtualMachines/jdk-11.0.2.jdk/Contents/Home

generate key

sudo keytool -genkey -v -keystore my-release-key.keystore -alias my-key-alias -keyalg RSA -keysize 2048 -validity 10000

assume key name is firebase-detox

sudo keytool -genkeypair -v -keystore firebase-detox.keystore -alias firebase-detox -keyalg RSA -keysize 2048 -validity 10000

Enter password. Do not forget it (password firebasedetox)

IAM_Management_Console

Setting up gradle variables

Move keystore to your android/app

sudo mv firebase-detox.keystore ~/workspace/FirebaseDetox/android/app/firebase-detox.keystore

open file android/gradle.properties. Follow this structure

MYAPP_RELEASE_STORE_FILE=my-release-key.keystore
MYAPP_RELEASE_KEY_ALIAS=my-key-alias
MYAPP_RELEASE_STORE_PASSWORD=*****
MYAPP_RELEASE_KEY_PASSWORD=*****

  • ***** is your keystore password when you generate the keystore. Example my keystore password is firebasedetox
MYAPP_RELEASE_STORE_FILE=firebase-detox.keystore
MYAPP_RELEASE_KEY_ALIAS=firebase-detox
MYAPP_RELEASE_STORE_PASSWORD=firebasedetox
MYAPP_RELEASE_KEY_PASSWORD=firebasedetox

Open android/app/build.gradle

Add code

...
android {
    ...
    defaultConfig { ... }
    signingConfigs {
        release {
            if (project.hasProperty('MYAPP_RELEASE_STORE_FILE')) {
                storeFile file(MYAPP_RELEASE_STORE_FILE)
                storePassword MYAPP_RELEASE_STORE_PASSWORD
                keyAlias MYAPP_RELEASE_KEY_ALIAS
                keyPassword MYAPP_RELEASE_KEY_PASSWORD
            }
        }
    }
    buildTypes {
        release {
            ...
            signingConfig signingConfigs.release
        }
    }
}
...

IAM_Management_Console

Then follow the document and setup Android Installation step by step

https://rnfirebase.io/docs/v5.x.x/installation/android

https://rnfirebase.io/docs/v5.x.x/auth/android

Follow the image to get all the SHA 1

IAM_Management_Console

Put the SHA 1

IAM_Management_Console

Download google-service.json

IAM_Management_Console

Drag google-service.json to app folder

IAM_Management_Console

###

IAM_Management_Console

Add Firebase SDK

Project-level build.gradle (/build.gradle):

buildscript {
  dependencies {
    // Add this line
    classpath 'com.google.gms:google-services:4.2.0'
  }
}

App-level build.gradle (//build.gradle):

dependencies {
  // Add this line
  implementation 'com.google.firebase:firebase-core:16.0.9'
}
...
// Add to the bottom of the file
apply plugin: 'com.google.gms.google-services'

After update need to sync gradle file

IAM_Management_Console

Go to android/app/src/main/java/com/[AppName]/MainApplication.java

import io.invertase.firebase.auth.RNFirebaseAuthPackage;

@Override
protected List<ReactPackage> getPackages() {

    ...

    packages.add(new RNFirebaseAuthPackage()); // here
    return packages;
}

IAM_Management_Console

###

IAM_Management_Console

run react-native run-android concurent to verify installation step

Follow step by step

https://rnfirebase.io/docs/v5.x.x/installation/android

https://rnfirebase.io/docs/v5.x.x/auth/android

Yay !!! Done