UNPKG

24.1 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 }
42 ```
43
44- **macOS Platform:**
45
46 Autolinking is not yet available on macOS. See the [Manual linking steps for macOS](#manual-linking-macos) below.
47
48<details id='manual-linking-macos'>
49<summary>Manually link the library on macOS</summary>
50
511. Open your project `.xcodeproj` on xcode.
52
532. Right click on the Libraries folder and select `Add files to "yourProjectName"`.
54
553. Add `RNCNetInfo.xcodeproj` (located at `node_modules/@react-native-community/react-native-netinfo/macos`) to your project Libraries.
56
574. Go to `Build Phases -> Link Binary with Libraries` and add: `libRNCNetInfo-macOS.a`.
58
59</details>
60
61- **Windows Platform:**
62
63 Autolinking automatically works on RNW >= 0.63.
64
65## Minimum supported versions for windows
66
67- react-native-windows 0.63 or newer
68- MSVC build tools v142 (included in Visual Studio 2019) or newer
69- x86, x64, or arm64 are supported, arm (32-bit) is not supported
70
71
72## React Native Compatibility
73To use this library you need to ensure you are using the correct version of React Native.
74We support react-native 0.60+ with auto-linking.
75
76If you are using a version of React Native that is lower than 0.60 check older versions of this README for details,
77but no support will be provided.
78
79## Browser Compatilibity
80The 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.
81If 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.
82
83## Migrating from the core `react-native` module
84This 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:
85
86```javascript
87import { NetInfo } from "react-native";
88```
89
90to:
91
92```javascript
93import NetInfo from "@react-native-community/netinfo";
94```
95
96Note 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.
97
98## Usage
99Import the library:
100
101```javascript
102import NetInfo from "@react-native-community/netinfo";
103```
104
105Subscribe to network state updates:
106
107```javascript
108// Subscribe
109const unsubscribe = NetInfo.addEventListener(state => {
110 console.log("Connection type", state.type);
111 console.log("Is connected?", state.isConnected);
112});
113
114// Unsubscribe
115unsubscribe();
116```
117
118Get the network state once:
119
120```javascript
121NetInfo.fetch().then(state => {
122 console.log("Connection type", state.type);
123 console.log("Is connected?", state.isConnected);
124});
125```
126
127## API
128* **Types:**
129 * [`NetInfoState`](#netinfostate)
130 * [`NetInfoStateType`](#netinfostatetype)
131 * [`NetInfoCellularGeneration`](#netinfocellulargeneration)
132* **Methods:**
133 * [`fetch()`](#fetch)
134 * [`refresh()`](#refresh)
135 * [`addEventListener()`](#addeventlistener)
136 * [`useNetInfo()`](#usenetinfo)
137
138### Types
139
140#### `NetInfoState`
141Describes the current state of the network. It is an object with these properties:
142
143| Property | Type | Description |
144| --------------------- | --------------------------------------- | -------------------------------------------------------------------------------------------------- |
145| `type` | [`NetInfoStateType`](#netinfostatetype) | The type of the current connection. |
146| `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.|
147| `isInternetReachable` | `boolean`, `null` | If the internet is reachable with the currently active network connection. If unknown defaults to `null` |
148| `isWifiEnabled` | `boolean` | *(Android only)* Whether the device's WiFi is ON or OFF. |
149| `details` | | The value depends on the `type` value. See below. |
150
151The `details` value depends on the `type` value.
152
153##### `type` is `none` or `unknown`
154
155`details` is `null`.
156
157##### `type` is `wifi`
158
159`details` has these properties:
160
161| Property | Platform | Type | Description |
162| ----------------------- | --------------------------------- | --------- | -------------------------------------------------------------------------------------------------------------------------- |
163| `isConnectionExpensive` | Android, iOS, macOS, Windows, Web | `boolean` | If the network connection is considered "expensive". This could be in either energy or monetary terms. |
164| `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**. |
165| `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**. |
166| `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. |
167| `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. |
168| `subnet` | Android, iOS, macOS | `string` | The subnet mask in IPv4 format. May not be present if it cannot be determined. |
169| `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. |
170| `linkSpeed` | Android | `number` | The link speed in Mbps. |
171| `rxLinkSpeed` | Android | `number` | The current receive link speed in Mbps. (Android Q / API level 29 and above) |
172| `txLinkSpeed` | Android | `number` | The current transmit link speed in Mbps. (Android Q / API level 29 and above) |
173
174
175`*` Requires `wiFiControl` capability in appxmanifest. Without it, these values will be null.
176
177##### `type` is `cellular`
178
179`details` has these properties:
180
181| Property | Platform | Type | Description |
182| ----------------------- | --------------------------------- | ------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------- |
183| `isConnectionExpensive` | Android, iOS, macOS, Windows, Web | `boolean` | If the network connection is considered "expensive". This could be in either energy or monetary terms. |
184| `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. |
185| `carrier` | Android, iOS | `string` | The network carrier name. May not be present or may be empty if none can be determined. |
186
187##### `type` is `bluetooth`, `ethernet`, `wimax`, `vpn`, or `other`
188
189`details` has these properties:
190
191| Property | Type | Description |
192| ----------------------- | --------- | ------------------------------------------------------------------------------------------------------ |
193| `isConnectionExpensive` | `boolean` | If the network connection is considered "expensive". This could be in either energy or monetary terms. |
194
195#### `NetInfoStateType`
196Describes the current type of network connection. It is an enum with these possible values:
197
198| Value | Platform | Description |
199| ----------- | --------------------------------- | ---------------------------------------------------------- |
200| `none` | Android, iOS, macOS, Windows, Web | No network connection is active |
201| `unknown` | Android, iOS, macOS, Windows, Web | The network state could not or has yet to be be determined |
202| `cellular` | Android, iOS, Windows, Web | Active network over cellular |
203| `wifi` | Android, iOS, macOS, Windows, Web | Active network over Wifi |
204| `bluetooth` | Android, Web | Active network over Bluetooth |
205| `ethernet` | Android, macOS, Windows, Web | Active network over wired ethernet |
206| `wimax` | Android, Web | Active network over WiMax |
207| `vpn` | Android | Active network over VPN |
208| `other` | Android, iOS, macOS, Windows, Web | Active network over another type of network |
209
210#### `NetInfoCellularGeneration`
211Describes the current generation of the `cellular` connection. It is an enum with these possible values:
212
213| Value | Description |
214| --------- | ----------------------------------------------------------------------------------------------------------------- |
215| `null` | Either we are not currently connected to a cellular network or type could not be determined |
216| `2g` | Currently connected to a 2G cellular network. Includes CDMA, EDGE, GPRS, and IDEN type connections |
217| `3g` | Currently connected to a 3G cellular network. Includes EHRPD, EVDO, HSPA, HSUPA, HSDPA, and UTMS type connections |
218| `4g` | Currently connected to a 4G cellular network. Includes HSPAP and LTE type connections |
219| `5g` | Currently connected to a 5G cellular network. Includes NRNSA (iOS only) and NR type connections |
220
221#### `NetInfoConfiguration`
222The configuration options for the library.
223
224| Property | Type | Default | Description
225| ---------------------------- | --------------------------------- | ----------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
226| `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`.
227| `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 |
228| `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`. |
229| `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`. |
230| `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`. |
231| `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`. |
232| `reachabilityShouldRun` | `() => boolean` | `() => true` | A function which returns a boolean to determine if checkInternetReachability should be run. |
233| `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.
234| `useNativeReachability` | `boolean` | `true` | A flag indicating whether or not Netinfo should use native reachability checks, if available.
235
236
237### Methods
238
239#### `configure()`
240
241Configures the library with the given configuration. You only need to supply the properties which you want to change from the default values.
242
243Note 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.
244
245**Example:**
246```javascript
247NetInfo.configure({
248 reachabilityUrl: 'https://clients3.google.com/generate_204',
249 reachabilityTest: async (response) => response.status === 204,
250 reachabilityLongTimeout: 60 * 1000, // 60s
251 reachabilityShortTimeout: 5 * 1000, // 5s
252 reachabilityRequestTimeout: 15 * 1000, // 15s
253 reachabilityShouldRun: () => true,
254 shouldFetchWiFiSSID: true, // met iOS requirements to get SSID. Will leak memory if set to true without meeting requirements.
255 useNativeReachability: false
256});
257```
258
259#### `addEventListener()`
260
261Subscribe 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.
262
263| Parameter | Type | Description |
264| ----------- | ------------------------------------------------------------- | ----------------------------------------------------------------------- |
265| `listener` | `(state: `[`NetInfoState`](README.md#netinfostate))` => void` | The listener which will be called whenever the connection state changes |
266
267**Example:**
268```javascript
269// Subscribe
270const unsubscribe = NetInfo.addEventListener(state => {
271 console.log("Connection type", state.type);
272 console.log("Is connected?", state.isConnected);
273});
274
275// Unsubscribe
276unsubscribe();
277```
278
279#### `useNetInfo()`
280
281A [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.
282
283**Example:**
284```jsx
285import {useNetInfo} from "@react-native-community/netinfo";
286
287const YourComponent = () => {
288 const netInfo = useNetInfo();
289
290 return (
291 <View>
292 <Text>Type: {netInfo.type}</Text>
293 <Text>Is Connected? {netInfo.isConnected?.toString()}</Text>
294 </View>
295 );
296};
297```
298
299You 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.
300
301```jsx
302const YourComponent = () => {
303 const netInfo = useNetInfo({
304 reachabilityUrl: 'https://clients3.google.com/generate_204',
305 reachabilityTest: async (response) => response.status === 204,
306 reachabilityLongTimeout: 60 * 1000, // 60s
307 reachabilityShortTimeout: 5 * 1000, // 5s
308 reachabilityRequestTimeout: 15 * 1000, // 15s
309 reachabilityShouldRun: () => true,
310 shouldFetchWiFiSSID: true, // met iOS requirements to get SSID
311 useNativeReachability: false
312 });
313
314 // ...
315};
316```
317
318#### `fetch()`
319
320Returns a `Promise` that resolves to a [`NetInfoState`](README.md#netinfostate) object.
321
322**Example:**
323```javascript
324NetInfo.fetch().then(state => {
325 console.log("Connection type", state.type);
326 console.log("Is connected?", state.isConnected);
327});
328```
329
330You can optionally send an `interface` string so the `Promise` resolves to a [`NetInfoState`](README.md#netinfostate) from the [`NetInfoStateType`](#netinfostatetype) indicated in `interface` argument.
331
332```javascript
333NetInfo.fetch("wifi").then(state => {
334 console.log("SSID", state.details.ssid);
335 console.log("BSSID", state.details.bssid);
336 console.log("Is connected?", state.isConnected);
337});
338```
339
340#### `refresh()`
341
342Updates 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.
343
344**Example:**
345```javascript
346NetInfo.refresh().then(state => {
347 console.log("Connection type", state.type);
348 console.log("Is connected?", state.isConnected);
349});
350```
351
352This will also update subscribers using `addEventListener` and/or `useNetInfo`.
353
354## Troubleshooting
355
356### Errors when building on Android
357
358### Errors while running Jest tests
359
360If 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:
361
362```js
363setupFiles: ['<rootDir>/jest.setup.js']
364```
365
366You should then add the following to your Jest setup file to mock the NetInfo Native Module:
367
368```js
369import mockRNCNetInfo from '@react-native-community/netinfo/jest/netinfo-mock.js';
370
371jest.mock('@react-native-community/netinfo', () => mockRNCNetInfo);
372```
373
374### Issues with the iOS simulator
375
376There 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.
377
378### Switching between different Wi-Fi does not send events in iOS
379
380The 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:
381
382```js
383 useEffect(() => {
384 const subAppState = AppState.addEventListener("change", async (nextAppState) => {
385 if (IS_IOS_DEVICE && nextAppState=='active') {
386 let newNetInfo = await NativeModules.RNCNetInfo.getCurrentState('wifi');
387 //your code here
388 }
389 });
390 const unsubNetState = NetInfo.addEventListener(state => {
391 //your code here
392 });
393 return () => {
394 if (subAppState) {
395 subAppState.remove();
396 }
397 unsubNetState();
398 };
399 },[]);
400```
401
402## Maintainers
403
404* [Mike Hardy](https://github.com/mikehardy)
405
406### Maintainers Emeritus
407
408* [Matt Oakes](https://github.com/matt-oakes) - [Freelance React Native Developer](http://mattoakes.net)
409* [Mike Diarmid](https://github.com/salakar) - [Invertase](https://invertase.io)
410
411## Contributing
412
413Please see the [contributing guide](/CONTRIBUTING.md).
414
415## License
416
417The library is released under the MIT license. For more information see [`LICENSE`](/LICENSE).