-
Notifications
You must be signed in to change notification settings - Fork 272
/
checkInternetConnection.js
43 lines (40 loc) · 1.3 KB
/
checkInternetConnection.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
/* @flow */
import { Platform, NetInfo } from 'react-native';
import checkInternetAccess from './checkInternetAccess';
/**
* Utility that allows to query for internet connectivity on demand
* On iOS, the listener is fired immediately after registration
* On Android, we need to use `isConnected.fetch`, that returns a promise which resolves with a boolean
* @param timeout
* @param url
* @returns {Promise<boolean>}
*/
export default function checkInternetConnection(
timeout: number = 3000,
url: string = 'http://www.google.com/',
): Promise<boolean> {
let connectionChecked: Promise<boolean>;
if (Platform.OS === 'ios') {
connectionChecked = new Promise((resolve: Function) => {
const handleFirstConnectivityChangeIOS = (isConnected: boolean) => {
NetInfo.isConnected.removeEventListener(
'connectionChange',
handleFirstConnectivityChangeIOS,
);
resolve(isConnected);
};
NetInfo.isConnected.addEventListener(
'connectionChange',
handleFirstConnectivityChangeIOS,
);
});
} else {
connectionChecked = NetInfo.isConnected.fetch();
}
return connectionChecked.then((isConnected: boolean) => {
if (isConnected) {
return checkInternetAccess(timeout, url);
}
return Promise.resolve(false);
});
}