UNPKG

24.2 kBMarkdownView Raw
1
2# `@react-native-community/netinfo`
3
4[![Actions](https://github.com/react-native-netinfo/react-native-netinfo/actions/workflows/ci.yml/badge.svg)](https://github.com/react-native-netinfo/react-native-netinfo/actions/workflows/ci.yml) ![Supports Android, iOS, macOS, Windows and Web](https://img.shields.io/badge/platforms-android%20|%20ios%20|%20macos%20|%20windows%20|%20web-lightgrey.svg) ![MIT License](https://img.shields.io/npm/l/@react-native-community/netinfo.svg) [![Lean Core Extracted](https://img.shields.io/badge/Lean%20Core-Extracted-brightgreen.svg)](https://github.com/facebook/react-native/issues/23313)
5
6React Native Network Info API for Android, iOS, macOS, Windows & Web. It allows you to get information on:
7
8* Connection type
9* Connection quality
10
11## Getting started
12Install the library using either Yarn:
13
14```
15yarn add @react-native-community/netinfo
16```
17
18or npm:
19
20```
21npm install --save @react-native-community/netinfo
22```
23
24#### Using React Native >= 0.60
25Linking the package manually is not required anymore with [Autolinking](https://github.com/react-native-community/cli/blob/master/docs/autolinking.md).
26
27- **iOS Platform:**
28
29 `$ npx pod-install` # CocoaPods on iOS needs this extra step
30
31- **Android Platform with AndroidX:**
32
33 Modify your **android/build.gradle** configuration:
34 ```
35 buildscript {
36 ext {
37 buildToolsVersion = "xx.yy.zz"
38 minSdkVersion = xyz
39 compileSdkVersion = xyz
40 targetSdkVersion = xyz
41 androidXCore = "1.7.0" // <-- Add this. Check versions here: https://developer.android.com/jetpack/androidx/releases/core
42 }
43 ```
44
45- **macOS Platform:**
46
47 Autolinking is not yet available on macOS. See the [Manual linking steps for macOS](#manual-linking-macos) below.
48
49<details id='manual-linking-macos'>
50<summary>Manually link the library on macOS</summary>
51
521. Open your project `.xcodeproj` on xcode.
53
542. Right click on the Libraries folder and select `Add files to "yourProjectName"`.
55
563. Add `RNCNetInfo.xcodeproj` (located at `node_modules/@react-native-community/react-native-netinfo/macos`) to your project Libraries.
57
584. Go to `Build Phases -> Link Binary with Libraries` and add: `libRNCNetInfo-macOS.a`.
59
60</details>
61
62- **Windows Platform:**
63
64 Autolinking automatically works on RNW >= 0.63.
65
66## Minimum supported versions for windows
67
68- react-native-windows 0.63 or newer
69- MSVC build tools v142 (included in Visual Studio 2019) or newer
70- x86, x64, or arm64 are supported, arm (32-bit) is not supported
71
72
73## React Native Compatibility
74To use this library you need to ensure you are using the correct version of React Native.
75We support react-native 0.60+ with auto-linking.
76
77If you are using a version of React Native that is lower than 0.60 check older versions of this README for details,
78but no support will be provided.
79
80## Browser Compatilibity
81The web implementation heavily depends on the [Network Information API](https://developer.mozilla.org/en-US/docs/Web/API/Network_Information_API) which is still an is an experimental technology and thus it's not supported in every browser.
82If this API is not available the library will safely fallback to the old [onLine](https://developer.mozilla.org/en-US/docs/Web/API/NavigatorOnLine/onLine) property and return basic connection information.
83
84## Migrating from the core `react-native` module
85This module was created when the NetInfo was split out from the core of React Native. To migrate to this module you need to follow the installation instructions above and then change you imports from:
86
87```javascript
88import { NetInfo } from "react-native";
89```
90
91to:
92
93```javascript
94import NetInfo from "@react-native-community/netinfo";
95```
96
97Note that the API was updated after it was extracted from NetInfo to support some new features, however, the previous API is still available and works with no updates to your code.
98
99## Usage
100Import the library:
101
102```javascript
103import NetInfo from "@react-native-community/netinfo";
104```
105
106Subscribe to network state updates:
107
108```javascript
109// Subscribe
110const unsubscribe = NetInfo.addEventListener(state => {
111 console.log("Connection type", state.type);
112 console.log("Is connected?", state.isConnected);
113});
114
115// Unsubscribe
116unsubscribe();
117```
118
119Get the network state once:
120
121```javascript
122NetInfo.fetch().then(state => {
123 console.log("Connection type", state.type);
124 console.log("Is connected?", state.isConnected);
125});
126```
127
128## API
129* **Types:**
130 * [`NetInfoState`](#netinfostate)
131 * [`NetInfoStateType`](#netinfostatetype)
132 * [`NetInfoCellularGeneration`](#netinfocellulargeneration)
133* **Methods:**
134 * [`fetch()`](#fetch)
135 * [`refresh()`](#refresh)
136 * [`addEventListener()`](#addeventlistener)
137 * [`useNetInfo()`](#usenetinfo)
138
139### Types
140
141#### `NetInfoState`
142Describes the current state of the network. It is an object with these properties:
143
144| Property | Type | Description |
145| --------------------- | --------------------------------------- | -------------------------------------------------------------------------------------------------- |
146| `type` | [`NetInfoStateType`](#netinfostatetype) | The type of the current connection. |
147| `isConnected` | `boolean`, `null` | If there is an active network connection. Defaults to `null` on most platforms for `unknown` networks. Note: Web browsers report network type `unknown` for many otherwise valid networks (https://caniuse.com/netinfo), so `isConnected` may be `true` or `false` and represent a real connection status even for unknown network types in certain cases.|
148| `isInternetReachable` | `boolean`, `null` | If the internet is reachable with the currently active network connection. If unknown defaults to `null` |
149| `isWifiEnabled` | `boolean` | *(Android only)* Whether the device's WiFi is ON or OFF. |
150| `details` | | The value depends on the `type` value. See below. |
151
152The `details` value depends on the `type` value.
153
154##### `type` is `none` or `unknown`
155
156`details` is `null`.
157
158##### `type` is `wifi`
159
160`details` has these properties:
161
162| Property | Platform | Type | Description |
163| ----------------------- | --------------------------------- | --------- | -------------------------------------------------------------------------------------------------------------------------- |
164| `isConnectionExpensive` | Android, iOS, macOS, Windows, Web | `boolean` | If the network connection is considered "expensive". This could be in either energy or monetary terms. |
165| `ssid` | Android, iOS (not tvOS), Windows | `string` | The SSID of the network. May not be present, `null`, or an empty string if it cannot be determined. **On iOS, your app must meet at least one of the [following requirements](https://developer.apple.com/documentation/systemconfiguration/1614126-cncopycurrentnetworkinfo?language=objc#discussion) and you must set the `shouldFetchWiFiSSID` configuration option or no attempt will be made to fetch the SSID. On Android, you need to have the `ACCESS_FINE_LOCATION` permission in your `AndroidManifest.xml` and accepted by the user**. |
166| `bssid` | Android, iOS (not tvOS), Windows* | `string` | The BSSID of the network. May not be present, `null`, or an empty string if it cannot be determined. **On iOS, make sure your app meets at least one of the [following requirements](https://developer.apple.com/documentation/systemconfiguration/1614126-cncopycurrentnetworkinfo?language=objc#discussion). On Android, you need to have the `ACCESS_FINE_LOCATION` permission in your `AndroidManifest.xml` and accepted by the user**. |
167| `strength` | Android, Windows | `number` | An integer number from `0` to `100` for the signal strength. May not be present if the signal strength cannot be determined. |
168| `ipAddress` | Android, iOS, macOS, Windows | `string` | The external IP address. Can be in IPv4 or IPv6 format. May not be present if it cannot be determined. |
169| `subnet` | Android, iOS, macOS | `string` | The subnet mask in IPv4 format. May not be present if it cannot be determined. |
170| `frequency` | Android, Windows* | `number` | Network frequency. Example: For 2.4 GHz networks, the method will return 2457. May not be present if it cannot be determined. |
171| `linkSpeed` | Android | `number` | The link speed in Mbps. |
172| `rxLinkSpeed` | Android | `number` | The current receive link speed in Mbps. (Android Q / API level 29 and above) |
173| `txLinkSpeed` | Android | `number` | The current transmit link speed in Mbps. (Android Q / API level 29 and above) |
174
175
176`*` Requires `wiFiControl` capability in appxmanifest. Without it, these values will be null.
177
178##### `type` is `cellular`
179
180`details` has these properties:
181
182| Property | Platform | Type | Description |
183| ----------------------- | --------------------------------- | ------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------- |
184| `isConnectionExpensive` | Android, iOS, macOS, Windows, Web | `boolean` | If the network connection is considered "expensive". This could be in either energy or monetary terms. |
185| `cellularGeneration` | Android, iOS, Windows | [`NetInfoCellularGeneration`](#netinfocellulargeneration) | The generation of the cell network the user is connected to. This can give an indication of speed, but no guarantees. |
186| `carrier` | Android, iOS | `string` | The network carrier name. May not be present or may be empty if none can be determined. |
187
188##### `type` is `bluetooth`, `ethernet`, `wimax`, `vpn`, or `other`
189
190`details` has these properties:
191
192| Property | Type | Description |
193| ----------------------- | --------- | ------------------------------------------------------------------------------------------------------ |
194| `isConnectionExpensive` | `boolean` | If the network connection is considered "expensive". This could be in either energy or monetary terms. |
195
196#### `NetInfoStateType`
197Describes the current type of network connection. It is an enum with these possible values:
198
199| Value | Platform | Description |
200| ----------- | --------------------------------- | ---------------------------------------------------------- |
201| `none` | Android, iOS, macOS, Windows, Web | No network connection is active |
202| `unknown` | Android, iOS, macOS, Windows, Web | The network state could not or has yet to be be determined |
203| `cellular` | Android, iOS, Windows, Web | Active network over cellular |
204| `wifi` | Android, iOS, macOS, Windows, Web | Active network over Wifi |
205| `bluetooth` | Android, Web | Active network over Bluetooth |
206| `ethernet` | Android, macOS, Windows, Web | Active network over wired ethernet |
207| `wimax` | Android, Web | Active network over WiMax |
208| `vpn` | Android | Active network over VPN |
209| `other` | Android, iOS, macOS, Windows, Web | Active network over another type of network |
210
211#### `NetInfoCellularGeneration`
212Describes the current generation of the `cellular` connection. It is an enum with these possible values:
213
214| Value | Description |
215| --------- | ----------------------------------------------------------------------------------------------------------------- |
216| `null` | Either we are not currently connected to a cellular network or type could not be determined |
217| `2g` | Currently connected to a 2G cellular network. Includes CDMA, EDGE, GPRS, and IDEN type connections |
218| `3g` | Currently connected to a 3G cellular network. Includes EHRPD, EVDO, HSPA, HSUPA, HSDPA, and UTMS type connections |
219| `4g` | Currently connected to a 4G cellular network. Includes HSPAP and LTE type connections |
220| `5g` | Currently connected to a 5G cellular network. Includes NRNSA (iOS only) and NR type connections |
221
222#### `NetInfoConfiguration`
223The configuration options for the library.
224
225| Property | Type | Default | Description
226| ---------------------------- | --------------------------------- | ----------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
227| `reachabilityUrl` | `string` | `https://clients3.google.com/generate_204` | The URL to call to test if the internet is reachable. Only used on platforms which do not supply internet reachability natively or if `useNativeReachability` is `false`.
228| `reachabilityMethod` | `NetInfoMethodType` | `HEAD` | The HTTP request method to use to call reachabilityUrl URL to call to test if the internet is reachable. Defaults to `HEAD`. `GET` is also available |
229| `reachabilityTest` | `(response: Response) => boolean` | `Promise.resolve(response.status === 204)` | A function which is passed the `Response` from calling the reachability URL. It should return `true` if the response indicates that the internet is reachable. Only used on platforms which do not supply internet reachability natively or if `useNativeReachability` is `false`. |
230| `reachabilityShortTimeout` | `number` | 5 seconds | The number of milliseconds between internet reachability checks when the internet was not previously detected. Only used on platforms which do not supply internet reachability natively or if `useNativeReachability` is `false`. |
231| `reachabilityLongTimeout` | `number` | 60 seconds | The number of milliseconds between internet reachability checks when the internet was previously detected. Only used on platforms which do not supply internet reachability natively or if `useNativeReachability` is `false`. |
232| `reachabilityRequestTimeout` | `number` | 15 seconds | The number of milliseconds that a reachability check is allowed to take before failing. Only used on platforms which do not supply internet reachability natively or if `useNativeReachability` is `false`. |
233| `reachabilityShouldRun` | `() => boolean` | `() => true` | A function which returns a boolean to determine if checkInternetReachability should be run. |
234| `shouldFetchWiFiSSID` | `boolean` | `false` | A flag indicating one of the requirements on iOS has been met to retrieve the network (B)SSID, and the native SSID retrieval APIs should be called. This has no effect on Android.
235| `useNativeReachability` | `boolean` | `true` | A flag indicating whether or not Netinfo should use native reachability checks, if available.
236
237
238### Methods
239
240#### `configure()`
241
242Configures the library with the given configuration. You only need to supply the properties which you want to change from the default values.
243
244Note that calling this will stop all previously added listeners from being called again. It is best to call this right when your application is started to avoid issues.
245
246**Example:**
247```javascript
248NetInfo.configure({
249 reachabilityUrl: 'https://clients3.google.com/generate_204',
250 reachabilityTest: async (response) => response.status === 204,
251 reachabilityLongTimeout: 60 * 1000, // 60s
252 reachabilityShortTimeout: 5 * 1000, // 5s
253 reachabilityRequestTimeout: 15 * 1000, // 15s
254 reachabilityShouldRun: () => true,
255 shouldFetchWiFiSSID: true, // met iOS requirements to get SSID. Will leak memory if set to true without meeting requirements.
256 useNativeReachability: false
257});
258```
259
260#### `addEventListener()`
261
262Subscribe to connection information. The callback is called with a parameter of type [`NetInfoState`](README.md#netinfostate) whenever the connection state changes. Your listener will be called with the latest information soon after you subscribe and then with any subsequent changes afterwards. You should not assume that the listener is called in the same way across devices or platforms.
263
264| Parameter | Type | Description |
265| ----------- | ------------------------------------------------------------- | ----------------------------------------------------------------------- |
266| `listener` | `(state: `[`NetInfoState`](README.md#netinfostate))` => void` | The listener which will be called whenever the connection state changes |
267
268**Example:**
269```javascript
270// Subscribe
271const unsubscribe = NetInfo.addEventListener(state => {
272 console.log("Connection type", state.type);
273 console.log("Is connected?", state.isConnected);
274});
275
276// Unsubscribe
277unsubscribe();
278```
279
280#### `useNetInfo()`
281
282A [React Hook](https://reactjs.org/docs/hooks-intro.html) which can be used to get access to the latest state. It returns a hook with the [`NetInfoState`](README.md#netinfostate) type.
283
284**Example:**
285```jsx
286import {useNetInfo} from "@react-native-community/netinfo";
287
288const YourComponent = () => {
289 const netInfo = useNetInfo();
290
291 return (
292 <View>
293 <Text>Type: {netInfo.type}</Text>
294 <Text>Is Connected? {netInfo.isConnected?.toString()}</Text>
295 </View>
296 );
297};
298```
299
300You can optionally send configuration when setting up the hook. Note that configuration is global for the library, so you shouldn't send different configuration for different hooks. It is instead recommended that you called `NetInfo.configure()` once when your project starts. The hook option is only provided as a convinience.
301
302```jsx
303const YourComponent = () => {
304 const netInfo = useNetInfo({
305 reachabilityUrl: 'https://clients3.google.com/generate_204',
306 reachabilityTest: async (response) => response.status === 204,
307 reachabilityLongTimeout: 60 * 1000, // 60s
308 reachabilityShortTimeout: 5 * 1000, // 5s
309 reachabilityRequestTimeout: 15 * 1000, // 15s
310 reachabilityShouldRun: () => true,
311 shouldFetchWiFiSSID: true, // met iOS requirements to get SSID
312 useNativeReachability: false
313 });
314
315 // ...
316};
317```
318
319#### `fetch()`
320
321Returns a `Promise` that resolves to a [`NetInfoState`](README.md#netinfostate) object.
322
323**Example:**
324```javascript
325NetInfo.fetch().then(state => {
326 console.log("Connection type", state.type);
327 console.log("Is connected?", state.isConnected);
328});
329```
330
331You can optionally send an `interface` string so the `Promise` resolves to a [`NetInfoState`](README.md#netinfostate) from the [`NetInfoStateType`](#netinfostatetype) indicated in `interface` argument.
332
333```javascript
334NetInfo.fetch("wifi").then(state => {
335 console.log("SSID", state.details.ssid);
336 console.log("BSSID", state.details.bssid);
337 console.log("Is connected?", state.isConnected);
338});
339```
340
341#### `refresh()`
342
343Updates NetInfo's internal state, then returns a `Promise` that resolves to a [`NetInfoState`](#netinfostate) object. This is similar to `fetch()`, but really only useful on platforms that do not supply internet reachability natively. For example, you can use it to immediately re-run an internet reachability test if a network request fails unexpectedly.
344
345**Example:**
346```javascript
347NetInfo.refresh().then(state => {
348 console.log("Connection type", state.type);
349 console.log("Is connected?", state.isConnected);
350});
351```
352
353This will also update subscribers using `addEventListener` and/or `useNetInfo`.
354
355## Troubleshooting
356
357### Errors when building on Android
358
359### Errors while running Jest tests
360
361If you do not have a Jest Setup file configured, you should add the following to your Jest settings and create the `jest.setup.js` file in project root:
362
363```js
364setupFiles: ['<rootDir>/jest.setup.js']
365```
366
367You should then add the following to your Jest setup file to mock the NetInfo Native Module:
368
369```js
370import mockRNCNetInfo from '@react-native-community/netinfo/jest/netinfo-mock.js';
371
372jest.mock('@react-native-community/netinfo', () => mockRNCNetInfo);
373```
374
375### Issues with the iOS simulator
376
377There is a [known](http://openradar.appspot.com/14585459) [issue](http://www.openradar.appspot.com/29913522) with the iOS Simulator which causes it to not receive network change notifications correctly when the host machine disconnects and then connects to Wifi. If you are having issues with iOS then please test on an actual device before reporting any bugs.
378
379### Switching between different Wi-Fi does not send events in iOS
380
381The SCNetworkReachability API used in iOS does not send events to the app in the background, so switching from one Wi-Fi network to another when your App was in background will not send an event and your network state will be out of sync with device state. To be sure you have up to date status when your app is in foreground again, you should re-fetch state each time when App comes to foreground, something like this:
382
383```js
384 useEffect(() => {
385 const subAppState = AppState.addEventListener("change", async (nextAppState) => {
386 if (IS_IOS_DEVICE && nextAppState=='active') {
387 let newNetInfo = await NativeModules.RNCNetInfo.getCurrentState('wifi');
388 //your code here
389 }
390 });
391 const unsubNetState = NetInfo.addEventListener(state => {
392 //your code here
393 });
394 return () => {
395 if (subAppState) {
396 subAppState.remove();
397 }
398 unsubNetState();
399 };
400 },[]);
401```
402
403## Maintainers
404
405* [Mike Hardy](https://github.com/mikehardy)
406
407### Maintainers Emeritus
408
409* [Matt Oakes](https://github.com/matt-oakes) - [Freelance React Native Developer](http://mattoakes.net)
410* [Mike Diarmid](https://github.com/salakar) - [Invertase](https://invertase.io)
411
412## Contributing
413
414Please see the [contributing guide](/CONTRIBUTING.md).
415
416## License
417
418The library is released under the MIT license. For more information see [`LICENSE`](/LICENSE).