How to check internet connection in React Native application for both iOS and Android?

后端 未结 7 2314
孤城傲影
孤城傲影 2021-02-07 12:52

I have a React Native application and I\'m seeking to add functionality that checks if there is an active internet connection when the app first starts up, and continuously ther

7条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-07 13:17

    Please read this https://reactnativeforyou.com/how-to-check-internet-connectivity-in-react-native-android-and-ios/ link.

    import React, { Component } from "react";
    import { View, Text, Button, Alert, NetInfo, Platform } from "react-native";
    
    export default class componentName extends Component {
      constructor(props) {
        super(props);
        this.state = {};
      }
    
      CheckConnectivity = () => {
        // For Android devices
        if (Platform.OS === "android") {
          NetInfo.isConnected.fetch().then(isConnected => {
            if (isConnected) {
              Alert.alert("You are online!");
            } else {
              Alert.alert("You are offline!");
            }
          });
        } else {
          // For iOS devices
          NetInfo.isConnected.addEventListener(
            "connectionChange",
            this.handleFirstConnectivityChange
          );
        }
      };
    
      handleFirstConnectivityChange = isConnected => {
        NetInfo.isConnected.removeEventListener(
          "connectionChange",
          this.handleFirstConnectivityChange
        );
    
        if (isConnected === false) {
          Alert.alert("You are offline!");
        } else {
          Alert.alert("You are online!");
        }
      };
    
      render() {
        return (
          
            

提交回复
热议问题