首页 > 解决方案 > 如何在 iOS 和 Android 的 React Native 应用程序中检查互联网连接?

问题描述

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

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

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

任何帮助表示赞赏;谢谢并保重。

标签: androidiosreact-nativepermissions

解决方案


请阅读此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>
    );
  }
}

推荐阅读