how to call a specific phone number from expo linking using firebase

Hello , i am John a new developer using expo for my application, i want to be a able to make a phone call to a specific number on my expo app, i tried linking this works andopens up the call dailer but it uses the static phone number given in the code, i want to be able to retrieve a phone number from my firebase database and that particular number would be opened in the dailer screen. for example if i build a delivery application and i have a registered person for delivery , i want the client to be able to call the delivery person from the app without having to copy and type any phone number

Hi

Basically you need to fetch the phone number from firebase. Then you need to call something like this:

Linking.openUrl(`tel:${phone}`)

So instead of using a hard coded number you should put the phone number in a variable and use the variable when calling Linking.openUrl().

Let me know if I have misunderstood your question, but if so, please post the relevant code you have so far.

Here’s an example showing the idea:

hi Michael, i have tried getting the number from firebase to no avail, i would appreciate it you can check my code and point me in the right direction thank you.

import React from ‘react’;

import { StyleSheet, Text, View ,Button,Image,TouchableHighlight,

   Dimensions,AppRegistry,TextInput,YellowBox,AppState,

   AsyncStorage,TouchableOpacity,Linking} from 'react-native';

import {Content,Container,Header,Left,Icon,Right,Body,Card} from ‘native-base’;

//import MapContainer from “…/MapContainer”;

import FooterComponent from “…/FooterComponent”;

import Fab from “…/Fab”;

import MapView,{ PROVIDER_GOOGLE ,AnimatedRegion} from ‘react-native-maps’;

//import GooglePlacesInput from ‘./RiderPlaceSearch’;

import * as firebase from ‘firebase’;

import ApiKeys from ‘…/constants/ApiKeys’;

//-----------------------------------------------------------------------------------//

/*

MAP COMPONENTS DEFINITION

*/

//-----------------------------------------------------------------------------------//

let { width, height } = Dimensions.get(‘window’);

const ASPECT_RATIO = width / height;

const LATITUDE = 0;

const LONGITUDE = 0;

const LATITUDE_DELTA = 0.1;

const LONGITUDE_DELTA = LATITUDE_DELTA * ASPECT_RATIO;

//-----------------------------------------------------------------------------------//

const taxiLogo = require(‘…/Images/taxi.png’)

export default class RiderHomeContents extends React.Component {

static DriverID;

static Firstname=“”;

static Lastname=“”;

static DriverPhone = “”;

static DriverPlateNum = “”;

//============================THIS PART SHOULD OPEN THE DAILER TO MAKE A PHONE CALL=======================//

dialCall = (DriverPhone) => {

firebase.database().ref('/Drivers/' +DriverID+'/Details').once('value').then(function(snapshot) {

  // RiderHomeContents.Firstname = snapshot.child('firstname').val();

 //  RiderHomeContents.Lastname = snapshot.child('lastname').val();

   RiderHomeContents.DriverPhone = snapshot.child('phone').val();

   //RiderHomeContents.DriverPlateNum = snapshot.child('plateNum').val();

          

   })

let phoneNumber = '';

if (Platform.OS === 'android') { phoneNumber = `tel:${DriverPhone}`; }

else {phoneNumber = `telprompt:${DriverPhone}`; }

Linking.openURL(phoneNumber);

  };

//========================================================================================================//

//------------CONSTRUCTOR-------------------- //

constructor(props) {

 super(props);

 this.state = {

   region: {

         latitude: LATITUDE,

         longitude: LONGITUDE,

         latitudeDelta: LATITUDE_DELTA,

         longitudeDelta: LONGITUDE_DELTA,

   },

   isModalVisible : false,

   isConfirmButton:true,

   isMounted: true,

 };

 if (!firebase.apps.length) {

   firebase.initializeApp(ApiKeys.FirebaseConfig);

 }

}

//------------NAVIGATION OPTION--------------------//

static navigationOptions= {

  drawerIcon: ({ tintColor }) => (

    <Image

          source={require('../Images/home.png')}

          style={{width:25,height:25}}

    />

  ),

}

//-----------COMPONENTDIDMOUNT------------------//

componentDidMount() {

//this.isMounted = true;



  navigator.geolocation.getCurrentPosition(

    position => {

      this.setState({

        region: {

          latitude: position.coords.latitude,

          longitude: position.coords.longitude,

          latitudeDelta: LATITUDE_DELTA,

          longitudeDelta: LONGITUDE_DELTA,

        }

      });

    },

  (error) => console.log(error.message),

  { enableHighAccuracy: true, timeout: 20000, maximumAge: 1000 },

  );

  this.watchID = navigator.geolocation.watchPosition(

    position => {

      this.setState({

        region: {

          latitude: position.coords.latitude,

          longitude: position.coords.longitude,

          latitudeDelta: LATITUDE_DELTA,

          longitudeDelta: LONGITUDE_DELTA,

        }

      });

    },

    //error

    (error) => this.setState({ error: error.message }),

    { enableHighAccuracy: true, timeout: 20000, maximumAge: 1000, distanceFilter: 10 },

  );

       

  //

  //desable the warnings in yellow box

  YellowBox.ignoreWarnings([

  'Encountered an error loading page',

  ]);

  console.disableYellowBox = true;

}

//---------------------------------------------

//COMPONENT UPDATE

//---------------------------------------------

 componentDidUpdate(prevState) {

  this._getDriverRequestDetails();

// Typical usage (don’t forget to compare props):

if (this.state.region !== prevState.region)

{

   // AppState.addEventListener('change',this.storeUserLocation());

}

}

//----------------------------------------------

//----------------------------------------------

componentWillUnmount() {

//  this.isMounted = false;

//  if(!this.state.isMounted){

  navigator.geolocation.clearWatch(this.watchID);

//  }

}

//------------RENDER FUNCTION--------------------//

render() {

const region = 

{

  latitude:LATITUDE,

  longitude:LONGITUDE,

  latitudeDelta:LATITUDE_DELTA,

  longitudeDelta:LONGITUDE_DELTA

}



return (

  <Container>

          

   <Header style={{backgroundColor:'#42A5F5',height:55}}>

      <Left>

      <TouchableHighlight

           style={{width:50,height:50,borderRadius:50,alignItems:'center',justifyContent:'center',marginTop:5}}

           onPress={() => this.props.navigation.toggleDrawer()}

       >

      <Icon

           name="menu"

           style={{color:'#ffffff',}}

       / >

      </TouchableHighlight>

      </Left>

      <Body>

            <Text style={{color:'#ffffff',fontSize:20,fontWeight:'bold',marginTop:20,marginLeft:90}}>Go App</Text>

      </Body>

      <Right>

      

      <Icon

           name="car"

           style={{color:'#ffffff',}}

       / >

    

      </Right>

   </Header>

  <Content>

   

  <View style={{justifyContent:'center'}}>

  

  <MapView

            provider={PROVIDER_GOOGLE}

            style={{flex:1}, styles.map}

            showsUserLocation={ true }

            // initialRegion{{}}

            showsBuildings={true}

            region={ this.state.region }

            onRegionChange={ region => this.setState({region}) }

            onRegionChangeComplete={ region => this.setState({region}) }

  >

    

       <MapView.Marker

          coordinate={ this.state.region}

          pinColor="#E91E63"

       >

               

    </MapView.Marker>

    

  </MapView>

        

  {this.state.isModalVisible ?

  

  <Card style={styles.MainAcceptView} >

    <View style={styles.DriverDetails}>

    <Image  source={require('../Images/avatar.png')} style={{width:50,height:50,borderRadius:50,marginTop:20,marginLeft:7}}  />

    <Text style={{marginTop:20,fontSize:18,marginLeft:15,color:'#636e72',fontWeight:"bold"}}>{"Driver Details: \n\ " + RiderHomeContents.Firstname +"  "+RiderHomeContents.Lastname +" \n\ \n\ "+RiderHomeContents.DriverPhone  +" \n\ \n\ "+RiderHomeContents.DriverPlateNum}</Text>

    <TouchableOpacity onPress={this.dialCall} activeOpacity={0.7} style={styles.button} >

      <Text style={styles.TextStyle}>CALL</Text>

    </TouchableOpacity>

    </View>

       

   </Card>

   

   :null

  }

  </View>

      

  </Content>

        

  <Fab onPressedAction={()=> this.props.navigation.navigate('pickUpLocation')}/>

        

 <FooterComponent/>

     

  </Container>

);

}

_pickUpLocation =() => {

this.props.navigation.navigate(‘pickUpLocation’);

alert(this.state.region.latitude);

};

//=================================================================This gets drivers details and displays them================//

_getDriverRequestDetails=async()=>{

AsyncStorage.getItem(‘riderId’)

.then(result =>

firebase.database().ref(‘/Ride_Request/’ +result).once(‘value’).then(function(snapshot) {

if(snapshot.exists()){

  DriverID= snapshot.child("driverID").val();

  DriverPhone=snapshot.child("phone").val();

  DriverPlateNum=snapshot.child("plateNum").val();

  

}

       

}).then(()=>{

  if(!DriverID==""){

    this.setState({isModalVisible:true});

  }

   

    firebase.database().ref('/Drivers/' +DriverID+'/Details').once('value').then(function(snapshot) {

      RiderHomeContents.Firstname = snapshot.child('firstname').val();

      RiderHomeContents.Lastname = snapshot.child('lastname').val();

      RiderHomeContents.DriverPhone = snapshot.child('phone').val();

      RiderHomeContents.DriverPlateNum = snapshot.child('plateNum').val();

                

      }).then(()=>{

       //console.log("firstname"+RiderHomeContents.Firstname);



      },(error)=>{

       // console.error("error"+error);

       // console.log("the user id:"+userId);

      })



      },(error)=>{

        console.error("error"+error);

        //console.log("the user id:"+userId);

      })

)

.catch(e =>

console.log(‘err’, e)

);

firebase.database().ref(‘/Ride_confirm/’ +result).once(‘value’).then(function(snapshot) {

if(snapshot.exists()){

this.setState({isModalVisible:true});

}

}).then(()=>{

console.log("")

})

.catch(e =>

console.log(‘err’, e)

);

}

//========================================= this is for driver details=====================//

storeUserLocation(){

  //------------------------Comment

// var userLatitude=this.state.region.latitude;

//var userLongitude=this.state.region.longitude;

//if(userLatitude>0 && userLongitude>0){

//------------------------here out if it still does not work

RiderID=firebase.auth().currentUser.uid;

if(RiderID){

firebase.database().ref(`Riders/${RiderID}/RiderCurrentLocation/`).set({

 latitude:this.state.region.latitude,

 longitude: this.state.region.longitude

 }).then(()=>{

  //firebase.database().ref(`Payments/${RiderID}/PaymentsHistory`);

  //Toast.show("payments updated successfully",Toast.SHORT);

  console.log("latitude:"+this.state.region.latitude +"   longitude:"+this.state.region.latitude);

 },(error)=>{

  //Toast.show(error.message,Toast.SHORT);

  console.log("error with location:"+error);

 });

}

//}

}

}

//------------ STYLESHEET--------------------//

const styles=StyleSheet.create({

         containerView:{

           flex:1,

           backgroundColor:'#ffffff'

         },

         footer:{

           backgroundColor:'#ffffff',

           height:60,

           

         },

         map: {

            flex : 1,

            height: 790,

            marginTop:0

            

         },

         MainAcceptView:{

          flexDirection:'row',

          backgroundColor:'white',

          width:350,

          height:210,

          position:"absolute",

          top:380,

          left:3,

          borderRadius:5,

          elevation:8

        },

        DriverDetails:{

          flexDirection:'row',

          position:'absolute'

     },

         searchBoxView:{

          flex:1,

           flexDirection:'row',

           backgroundColor:'white',

           width:320,

           minHeight:50,

           position:"absolute",

           top:10,

           left:20,

           borderRadius:5,

           elevation:5

         },

         searchIcon:{

           color:'#42A5F5',

           marginTop:12,

           marginLeft:10

         },

         DropUpLocation:{

          flex:1,

           alignSelf:'stretch',

           width:280,

           paddingBottom:2,

           marginTop:-3,

           marginLeft:8,

           backgroundColor:'#fff',

           fontSize:17

         },

         pickupImage:{

          marginLeft:8,

          marginTop:10,

          width:25,

          height:25,

         },

         button: {

          width: '80%',

          padding: 6,

          backgroundColor: '#4130E6',

          borderRadius: 7,

        },

         DoneButton:{

          flex:1,

          alignItems:'center',

          justifyContent:'center',

          backgroundColor:'#56ab2f',

          height:50,

          borderRadius: 200 / 2,

          width:150,

          marginTop:5,

          marginLeft:3

        }

});

AppRegistry.registerComponent(‘RiderHomeContents’, () =>RiderHomeContents);Preformatted text

firebase.auth().settings.appVerificationDisabledForTesting = true;

var phoneNumber = “+16505554567”;
var testVerificationCode = “123456”;

// This will render a fake reCAPTCHA as appVerificationDisabledForTesting is true.
// This will resolve after rendering without app verification.
var appVerifier = new firebase.auth.RecaptchaVerifier(‘recaptcha-container’);
// signInWithPhoneNumber will call appVerifier.verify() which will resolve with a fake
// reCAPTCHA response.
firebase.auth().signInWithPhoneNumber(phoneNumber, appVerifier)
.then(function (confirmationResult) {
// confirmationResult can resolve with the whitelisted testVerificationCode above.
return confirmationResult.confirm(testVerificationCode)
}).catch(function (error) {
// Error; SMS not sent
// …
});

Alfred0809 thank you for replying but i don’t have a problem with Auth and phone verification, what i need is a means where you click a button and then make a phone call, upon clicking the button the app opens the dailer and a specific phone number is copied from the database to the phone dailer

bro same thing i need.

I eventually came up with a solution for this if you could message me via email I could guide you better johnenokela199521@gmail.com