Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ionic 3 - how use cordova plugin Network interface with ionic?

My problem: I need my app to search the local WiFi network to find a server computer with a application on a specific port. I don't want to hard code the server IP address into the app as it could be possibly used in many locations.

Update: So I need to be able to find the IP address of all devices on the network.

What iv done so far:

Iv followed other guides on stack overflow and online by doing the following steps:

1. install cordova plugin:

 "cordova plugin add cordova-plugin-networkinterface"

2. Declare the variable in global scope to access the object

declare var NetworkInterface: any;
export class TestClass{}

3. Call the object using the global variable inside a component

NetworkInterface.getWiFiIPAddress((ip) => {
   console.log("network ip address = " + ip);
});

However this causes an error on run time when running from the mobile:

ERROR Error: Uncaught (in promise): ReferenceError: NetworkInterface is not defined

I've also tried declaring a variable globally and then trying to apply a string value in a component, only to get the same problem. It appears to be more of a problem with the variable not working globally? Any help would be great!

like image 818
niroice Avatar asked Mar 07 '23 10:03

niroice


1 Answers

You need to use below CLI:

ionic plugin add cordova-plugin-networkinterface --save 

You need to declare it as global.And also you need to test this on either device or emulator since this is a plugin.

 declare var NetworkInterface: any;

Old Answer:

You can easily do it using native Network plugin.

ionic cordova plugin add cordova-plugin-network-information
npm install --save @ionic-native/network

From the doc:

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

constructor(private network: Network) { }

...

// watch network for a connection
let connectSubscription = this.network.onConnect().subscribe(() => {
  console.log('network connected!');
  // We just got a connection but we need to wait briefly
   // before we determine the connection type. Might need to wait.
  // prior to doing any api requests as well.
  setTimeout(() => {
    if (this.network.type === 'wifi') {
      console.log('we got a wifi connection, woohoo!');
    }
  }, 3000);
});
like image 97
Sampath Avatar answered Mar 10 '23 02:03

Sampath