【问题标题】:How to check internet connection in React Native application for both iOS and Android?如何在 iOS 和 Android 的 React Native 应用程序中检查互联网连接?
【发布时间】:2019-12-09 07:51:03
【问题描述】:

我有一个 React Native 应用程序,我正在寻求添加功能,以检查应用程序首次启动时是否存在活动的互联网连接,并在此后不断地检查。

如果没有互联网连接,我正在寻求显示一条消息“未检测到互联网连接”,并带有“重试”按钮;如果有互联网连接,我正在寻找加载页面(WebView)。

我也在寻求同时支持 iOS 和 Android 设备;我对此进行了独立研究,并在 GitHub 上找到了几个库。但是,许多需要在 Android Manifest XML 中添加权限的额外步骤,但是我在我的应用程序中看不到 Android Manifest XML 文件;为什么只有 Android 需要清单?

感谢任何帮助;谢谢并保重。

【问题讨论】:

标签: android ios react-native permissions


【解决方案1】:

请阅读此https://reactnativeforyou.com/how-to-check-internet-connectivity-in-react-native-android-and-ios/ 链接。

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 (
      <View>
        <Button
          onPress={() => this.CheckConnectivity()}
          title="Check Internet Connectivity"
          color="#841584"
          accessibilityLabel="Learn more about this purple button"
        />
      </View>
    );
  }
}

【讨论】:

  • 这很有帮助;但是,如何在没有按钮的情况下持续检查互联网连接(如果互联网连接状态发生变化,则触发操作)?
  • 那是连接改变的回调NetInfo.isConnected.addEventListener( "connectionChange", this.handleFirstConnectivityChange );handleFirstConnectivityChange = isConnected =&gt; { //NetInfo.isConnected.removeEventListener("connectionChange",this.handleFirstConnectivityChange); if (isConnected === false) { Alert.alert("You are offline!"); } else { Alert.alert("You are online!"); } };
  • 好的;但是,该代码在哪里(在 handleFirstConnectivityChange 方法中?)
  • 连接改变时调用whenhandleFirstConnectivityChange()方法
  • NetInfo 不再是 react-native 项目的一部分。它从核心中分离出来。你可以使用这个例子 -> stackoverflow.com/a/64295620/1953383
【解决方案2】:

我今天遇到了这个问题,并找到了我认为最好的解决方案。 它会不断搜索网络变化并相应地显示它们。

我使用 expo install @react-native-community/netinfo 对其进行了测试,它的工作完美无缺

import {useNetInfo} from "@react-native-community/netinfo";
import {View, Text} from "react-native";
const YourComponent = () => {
  const netInfo = useNetInfo();

  return (
    <View>
      <Text>Type: {netInfo.type}</Text>
      <Text>Is Connected? {netInfo.isConnected.toString()}</Text>
    </View>
  );
};

【讨论】:

    【解决方案3】:

    似乎这个问题遍布stackoverflow,似乎没有人关注其他现有答案。

    您应该使用“@react-native-community/netinfo”库。 NetInfo 曾经是 react-native 的一部分,但后来它从核心中分离出来。如果您想观察网络状态变化,只需使用提供的 addEventListener 方法即可。

    import NetInfo from "@react-native-community/netinfo";
    
    NetInfo.fetch().then(state => {
        console.log("Connection type", state.type);
        console.log("Is connected?", state.isConnected);
    });
    
    const unsubscribe = NetInfo.addEventListener(state => {
        console.log("Connection type", state.type);
        console.log("Is connected?", state.isConnected);
    });
    
    // Unsubscribe
    unsubscribe();
    

    【讨论】:

    • ? 这应该是答案!
    • 我在 Android 中打开/关闭 wifi 或在 wifi 和蜂窝网络之间切换时遇到问题。状态值未更新。
    • @JeafGilbert 你是在后台还是前台做的?也许你可以粘贴代码?我假设当您打开选项时,应用程序会进入后台,这将需要在后台任务中使用不同的侦听器。这也可能与休眠问题有关。 github.com/react-native-netinfo/react-native-netinfo/issues/537
    • 原来是从 v6.0.0 更新到 v.7.1.7 导致了这种情况。所以我将它回滚到 v6.0.0 并再次工作。
    【解决方案4】:

    为此 react-native 提供一个名为 netinfo 的库:请查看:https://github.com/react-native-community/react-native-netinfo

    它提供了一个 api 来检查连接及其类型。

    注意:如果您使用的是 RN https://facebook.github.io/react-native/docs/netinfo.html

    【讨论】:

      【解决方案5】:

      NetInfo 已从 React-Native 中删除。现在可以从“react-native-netinfo”而不是“react-native”安装和导入它。 见https://github.com/react-native-community/react-native-netinfo

      【讨论】:

      • 这不是@NSA问题的答案
      • 对不起,我通过提供新信息完成了第一个答案:)
      【解决方案6】:

      创建 NetworkUtills.js

      import NetInfo from "@react-native-community/netinfo";
      export default class NetworkUtils {
        static async isNetworkAvailable() {
          const response = await NetInfo.fetch();
          return response.isConnected;
      }}
      

      像这样在任何地方使用

      const isConnected = await NetworkUtils.isNetworkAvailable()
      

      【讨论】:

        【解决方案7】:

        这是一个关于如何检查您的应用是否可以访问互联网的最新解决方案。

        首先安装官方NetInfo社区包:

        yarn add @react-native-community/netinfo
        

        然后是sn-p。

        import { Platform } from "react-native";
        import NetInfo from "@react-native-community/netinfo";
        ...
        
        
        const checkConnectivity = (): Promise<boolean | null> => {
            return new Promise(resolve => {
                // For Android devices
                if (Platform.OS === "android") {
                    NetInfo.fetch().then(state => {
                        resolve(state.isInternetReachable);
                    });
                } else {
                    // For iOS devices
                    const unsubscribe = NetInfo.addEventListener(state => {
                        unsubscribe();
                        resolve(state.isInternetReachable);
                    });
                }
            });
        };
        
        ...
        

        它的用法

        ...
        const hasInternet = await checkConnectivity();
        
        if(hasInternet) {
           // My app can reach the internet
        } 
        else {
          // Can't connect to the internet. Too bad!
        }
        
        

        【讨论】:

          【解决方案8】:

          世博会:

          import NetInfo from "@react-native-community/netinfo";
          
          export const checkConnected = () => {
            return NetInfo.fetch().then((state) => {
              console.log("Connection type", state.type);
              console.log("Is connected?", state.isConnected);
              return state.isConnected;
            });
          };
          

          查看此文档:https://docs.expo.dev/versions/latest/sdk/netinfo/

          【讨论】:

            【解决方案9】:

            Android 清单文件在这里: \android\app\src\main\AndroidManifest.xml。 进一步使用这个库来做你的要求 https://github.com/react-native-community/react-native-netinfo

            【讨论】:

              【解决方案10】:

              我正在使用 react-native 0.66.3 我已将此代码添加到启动画面,因此当 NetInfo 返回“isConnected:false”时,我会显示“重试”按钮以检查网络 如果网络已连接,导航将替换为主屏幕。

              这是我的启动画面:

              import React, { useEffect, useState } from "react";
              ...
              import NetInfo from "@react-native-community/netinfo";
              
              const Splash = (props) => {
                const [network, setNetwork] = useState('')
                const [loading, setLoading] = useState(false);
              
                useEffect(() => {
                  unsubscribe()
                }, []);
              
                function unsubscribe() {
                  NetInfo.fetch().then(state => {
                    setNetwork(state)
                    setTimeout(function () {
                      if (state.isConnected) {
                        // any thing you want to load before navigate home screen
                      } else {
                        setLoading(false)
                      }
                    }, 500);
                  })
                };
              
              
              
                return (
                  <View style={{
                    flex: 1,
                    backgroundColor: global.bgBody,
                    justifyContent: 'center',
                    alignItems: 'center'
                  }}>
                    <Image
                      source={Logo}
                      style={{
                        width: 150,
                        height: 123,
                      }}
                    />
                    {!network?.isConnected || loading ? <View style={{ marginTop: 30 }}>
                      <Description text={`Please check your internet connection and try again`} />
                      <Button
                        title="Try Again"
                        onPress={() => {
                          setLoading(true)
                          unsubscribe()
                        }}
                        loading={loading}
                      />
                    </View> : null}
                  </View>
                );
              };
              export default Splash;
              

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 2013-08-08
                • 1970-01-01
                • 1970-01-01
                • 2014-05-21
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2013-02-02
                相关资源
                最近更新 更多