Monday, May 20, 2024
76
rated 0 times [  82] [ 6]  / answers: 1 / hits: 17802  / 7 Years ago, tue, april 4, 2017, 12:00:00

I need to check Internet connection in react native iOS



I would try following code:



NetInfo.isConnected.fetch().then(isConnected => {
console.log(isConnected);
});


that can work fine in react native android application,
But it always return 'false' in react native iOS .


More From » react-native

 Answers
3

There is currently an open issue about this in react native's github.



You can see the discussion there, but in short - the fetch is always returning false, but you can work around it by listening to the connection changed event.



Code example from there:



componentDidMount() {
NetInfo.isConnected.addEventListener('change', this.handleConnectionChange);

NetInfo.isConnected.fetch().done(
(isConnected) => { this.setState({ status: isConnected }); }
);
}

componentWillUnmount() {
NetInfo.isConnected.removeEventListener('change', this.handleConnectionChange);
}

handleConnectionChange = (isConnected) => {
this.setState({ status: isConnected });
console.log(`is connected: ${this.state.status}`);
}


Edit:



Seems like this issue has been worked on.
Also, change event was renamed to connectionChange. Updated workaround code:



componentDidMount() {
NetInfo.isConnected.addEventListener('connectionChange', this.handleConnectionChange);

NetInfo.isConnected.fetch().done(
(isConnected) => { this.setState({ status: isConnected }); }
);
}

componentWillUnmount() {
NetInfo.isConnected.removeEventListener('connectionChange', this.handleConnectionChange);
}

handleConnectionChange = (isConnected) => {
this.setState({ status: isConnected });
console.log(`is connected: ${this.state.status}`);
}


Updated:



The change event type is deprecated. Consider using the connectionChange event type.


[#58279] Saturday, April 1, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
travion

Total Points: 137
Total Questions: 96
Total Answers: 103

Location: India
Member since Wed, Aug 4, 2021
3 Years ago
travion questions
Mon, Dec 16, 19, 00:00, 5 Years ago
Sat, Oct 19, 19, 00:00, 5 Years ago
Fri, Sep 20, 19, 00:00, 5 Years ago
Wed, Nov 14, 18, 00:00, 6 Years ago
Sun, Oct 28, 18, 00:00, 6 Years ago
;