DEV Community

Cover image for React Native WiFi Connect
RamR
RamR

Posted on

React Native WiFi Connect

Establish WiFi connection in a React native application.

Packages

  • react-native-permissions config
  • @react-native-community/geolocation config
  • react-native-wifi-reborn config
  • @react-native-tethering/wifi config

Note, we need location permission to connect wifi.

Front Page



import React, { useState } from 'react';
import {
  View,
  Text,
  StyleSheet,
  PermissionsAndroid,
  Platform,
} from 'react-native';

import { TextInput, Button } from 'react-native-paper';

export default function App() {
  const [ssid, setSsid] = useState('');
  const [password, setPassword] = useState('');

  return (
    <View style={styles.container}>
      <Text style={styles.text}>Connect to Network</Text>
      <TextInput
        style={styles.input}
        label="SSID"
        value={ssid}
        onChangeText={(text) => setSsid(text)}
      />
      <TextInput
        style={styles.input}
        label="Password"
        value={password}
        onChangeText={(text) => setPassword(text)}
      />
      <Button
        icon="wifi"
        mode="contained"
        style={{ marginTop: 20 }}
        onPress={() => ()}>
        Connect
      </Button>
    </View>
  );
}



Enter fullscreen mode Exit fullscreen mode

Image description

Turn on Location



import { request, PERMISSIONS, RESULTS } from 'react-native-permissions';
import Geolocation from '@react-native-community/geolocation';

const isAndroid = Platform.OS === 'android';
export default function App() {
. . .
  const requestLocationPermission = async () => {
    var given = false;
    if (isAndroid) {
      try {
        const granted = await PermissionsAndroid.request(
          PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
          {
            title: 'Location Permission',
            message:
              'This app needs access to your location to manage wifi networks',
            buttonNeutral: 'Ask Me Later',
            buttonNegative: 'Cancel',
            buttonPositive: 'OK',
          }
        );
        if (granted === PermissionsAndroid.RESULTS.GRANTED) {
          console.log('GRANTED Location permission granted');
          given = true;
        } else {
          console.log('Location permission denied');
        }
      } catch (err) {
        console.warn(err);
      }
    } else {
      const result = await request(PERMISSIONS.IOS.LOCATION_WHEN_IN_USE);
      if (result === RESULTS.GRANTED) {
        console.log('IOS GRANTED Location permission granted');
        given = true;
      } else {
        Alert.alert('Location permission denied');
      }
    }
    return given;
  };

  const turnOnLocation = async () => {
    var permit = await requestLocationPermission();
    if (!permit) return false;
    var result = await new Promise((resolve, reject) => {
      Geolocation.getCurrentPosition(
        (position) => {
          console.log(position);
          resolve(true);
        },
        (error) => {
          console.log(error.code, error.message);
          resolve(false);
        },
        { enableHighAccuracy: true, timeout: 15000, maximumAge: 10000 }
      );
    });
    console.log('turnOnLocation result', result);
    return result;
  };
. . .


Enter fullscreen mode Exit fullscreen mode

Connect WiFi

Based on my experience, I figured out TetheringManager will do the job for android and WifiManager for iOS.

But while using TetheringManager the iOS app getting crashed. So I'm going to have 2 different files separately for android and iOS.

Let's rename the file as wificonnect.android.js and duplicate this file as wificonnect.ios.js.

wificonnect.android.js



import TetheringManager from "@react-native-tethering/wifi";

export default function App() {
. . .
  const requestLocationPermission = async () => {. . .};

  const turnOnLocation = async () => {. . .};

  const connectWifi = async () => {
    try {
      const granted = await turnOnLocation();
      if (granted) {
        const wifiEnabled = await TetheringManager.isWifiEnabled();

        if (!wifiEnabled) {
          await TetheringManager.setWifiEnabled();
          connectWifi();
          return;
        }

        await TetheringManager.connectToNetwork({
          ssid: ssid,
          password: password,
          isHidden: true,
        })
          .then(
            () => {
              console.log("wifi Connected successfully!");
              alert(" wifi network connected.");
            },
            (error) => {
              console.log("Connection failed! ", error);
              alert("unable to connect wifi\n\n" + error);
            }
          )
          .catch((err) => {
            console.log("Connection failed! ", err);
            alert("unable to connect wifi\n\n" + err);
          });
      } else {
        console.log(
          "unable to connect wifi\n\n" +
            "Location service is turned off or Location permission denied"
        );
        alert(
          "unable to connect wifi\n\n" +
            "Location service is turned off or Location permission denied"
        );
      }
    } catch (err1) {
      alert("unable to connect wifi\n\n" + err1);
    }
  };

  return (
. . .
    <Button
      icon="wifi"
      mode="contained"
      style={{ marginTop: 20 }}
      onPress={() => connectWifi()}
    >
      Connect
    </Button>
. . .
  );
}


Enter fullscreen mode Exit fullscreen mode

wificonnect.ios.js



import WifiManager from "react-native-wifi-reborn";
. . .
const connectWifi = async () => {
  try {
    const granted = await turnOnLocation();
    if (granted) {
      /**
         WifiManager.connectToProtectedSSID(ssid, password, try with both 'true' and 'false')
         */
      WifiManager.connectToProtectedSSID(ssid, password, true)
        .then(
          () => {
            console.log("wifi Connected successfully!");
            alert("wifi network connected.");
          },
          (error) => {
            console.log("Connection failed! ", error);
            alert("unable to connect wifi\n\n" + error);
          }
        )
        .catch((err) => {
          console.log("Connection failed! ", err);
          alert("unable to connect wifi\n\n" + err);
        });
    } else {
      console.log(
        "unable to connect wifi\n\n" +
          "Location service is turned off or Location permission denied"
      );
      alert(
        "unable to connect wifi\n\n" +
          "Location service is turned off or Location permission denied"
      );
    }
  } catch (err1) {
    alert("unable to connect wifi\n\n" + err1);
  }
};



Enter fullscreen mode Exit fullscreen mode

App.js



import WifiConnect from "./wificonnect"

export default function App() {
  return <WifiConnect />;
}



Enter fullscreen mode Exit fullscreen mode

Image description

Full code here

Thank You.

Top comments (0)