How to detect internet connection on Ionic?

Asked

Viewed 1,990 times

1

I’m using Ionic 3 along with the plugin network Ionic, I can detect when it is connected to an internet network by the plugin but I can not check if this network connected is internet or not, someone knows how I can do it?

1 answer

3


There is the plugin cited in the documentation itself: https://ionicframework.com/docs/native/network/ to install navigate to the project folder with cd and execute the commands, as in the example:

cd /home/user/projeto
ionic cordova plugin add cordova-plugin-network-information
npm install --save @ionic-native/network

Then in the src/app/app.module.ts add to providers, example:

import { Network } from '@ionic-native/network';

...

@NgModule({
  ...

  providers: [
    ...
    Network
    ...
  ]
  ...
})
export class AppModule { }

So where to use the module do this:

import { Network } from '@ionic-native/network';

constructor(private network: Network) { }

...

let disconnectSubscription = this.network.onDisconnect().subscribe(() => {
    console.log('Desconectado da internet');
});

let connectSubscription = this.network.onConnect().subscribe(() => {
    console.log('Conectado a internet!');
});

If you want to stop the observers use:

disconnectSubscription.unsubscribe();
connectSubscription.unsubscribe();

Note that it is not because you are connected to a network or mobile network that means your provider is sending you internet (providing you), a simpler test would be to use HttRequest and check if you can access any service url that interests your application.

For example (it is in php but can adapt easily) would create a simple page that would return anything, for example the word success:

<?php
echo 'success';

So the test would be something like:

import { HTTP } from '@ionic-native/http';

constructor(private http: HTTP) {}

...

this.http.get('http://meu-site.com/status.php', {}, {})
  .then(response => {
      if (response.data === 'success') {
          console.log('Serviço disponível');
      }
  })
  .catch(error => {
    console.log('Serviço indisponível');
    console.log("status:", error.status);
    console.log("descritivo:", error.error);
    console.log("headers:", error.headers);

  });
  • Yes, I had already thought about making a request but I thought there might be some other solution, thank you!

  • 1

    @Julianosouza the idea of the request can be used even to check other services, type on the server side check if the database is available, or even other dependencies, there would return a success, that would already check the internet and your server at the same time, see the edition of the answer.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.