首页指南参考教程

NetInfo

提供对网络信息的访问的跨平台 API。

Android
iOS
tvOS
Web

@react-native-community/netinfo 允许你获取有关连接类型和连接质量的信息。

¥@react-native-community/netinfo allows you to get information about connection type and connection quality.

安装

¥Installation

Terminal
npx expo install @react-native-community/netinfo

If you are installing this in an existing React Native app (bare workflow), start by installing expo in your project. Then, follow the additional instructions as mentioned by library's README under "Installation in bare React Native projects" section.

API

要导入该库,请使用:

¥To import this library, use:

import NetInfo from '@react-native-community/netinfo';

如果你只想获取有关网络连接的信息一次,你可以使用:

¥If you want to grab information about the network connection just once, you can use:

NetInfo.fetch().then(state => {
  console.log('Connection type', state.type);
  console.log('Is connected?', state.isConnected);
});

或者,如果你想订阅有关网络状态的更新(这样你就可以在网络状态发生变化时运行代码/执行操作),请使用:

¥Or, if you'd rather subscribe to updates about the network state (which then allows you to run code/perform actions anytime the network state changes) use:

const unsubscribe = NetInfo.addEventListener(state => {
  console.log('Connection type', state.type);
  console.log('Is connected?', state.isConnected);
});

// To unsubscribe to these update, just use:
unsubscribe();

访问 SSID

¥Accessing the SSID

要访问 ssid 属性(在 state.details.ssid 下可用),需要执行一些额外的配置步骤:

¥To access the ssid property (available under state.details.ssid), there are a few additional configuration steps:

安卓和 iOS

¥Android and iOS

仅限 iOS

¥iOS only

  • com.apple.developer.networking.wifi-info 权利添加到 ios.entitlements 下的 app.json 中:

    ¥Add the com.apple.developer.networking.wifi-info entitlement to your app.json under ios.entitlements:

    app.json
      "ios": {
        "entitlements": {
          "com.apple.developer.networking.wifi-info": true
        }
      }
    
  • 选中应用的应用标识符 可以在这里找到 中的访问 Wi-Fi 信息框。

    ¥Check the Access Wi-Fi Information box in your app's App Identifier, which can be found here.

  • 使用 eas build --platform iosnpx expo run:ios 重建你的应用。

    ¥Rebuild your app with eas build --platform ios or npx expo run:ios.

有关 API 和使用的更多信息,请参阅 react-native-netinfo 文档

¥For more information on API and usage, see react-native-netinfo documentation.

Expo 中文网 - 粤ICP备13048890号