Forem

Cover image for React Native WiFi Connect
RamR
RamR

Posted on

10

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.

Image of Datadog

The Future of AI, LLMs, and Observability on Google Cloud

Datadog sat down with Google’s Director of AI to discuss the current and future states of AI, ML, and LLMs on Google Cloud. Discover 7 key insights for technical leaders, covering everything from upskilling teams to observability best practices

Learn More

Top comments (0)

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay