Using WifiWizard2 with Ionic

I was creating an Android and iOS app which needed to connect to a Wifi access point so an IoT device could be configured.

The app was written in Angular which I was using along side the Ionic Framework.

After searching around to find a way to list the available Wifi Access Points I found the Cordova plugin WifiWizard2 which took over from the discontiued WifiWizard.

They had a demo showing how to use the plugin but it was wrtten in Meteor which I wasn't familiar with and I couldn't find many other examples. All I could find was other developers wondering how to use the plugin the same way I was intending.

After figuring it out I thought it best to share my example to hopefully help others.

Async function

Cordova calls are made asynchronously so the WifiWizard2.scan() function will need to be inside a try and catch statement, using await.

results = [];
async getNetworks() {
    try {
      let results = await WifiWizard2.scan();
      this.results = results;
    } catch (error) {

    }
}

As a test I'm calling this from an ion-button

<ion-button color="primary" (click)="getNetworks()">Get Networks</ion-button>

and then displaying the results in a list

  <ion-list>
    <ion-item *ngFor="let data of results">
        {{data.SSID}}
    </ion-item>
  </ion-list>

The missing step

The part that was missing from a some other examples I'd found was deplaring the WifiWizard2 plugin. To do this you just need to add the following after the imports

declare var WifiWizard2: any;

The Code

First of all you need to create a blank Ionic app with the platforms added. Then install the WifiWizrd2 plugin

ionic start myWifiApp blank

cd myWifiApp

ionic cordova prepare ios
ionic cordova prepare android

ionic cordova plugin add wifiwizard2

Replace the content form the file src/app/home/home.page.html so that is looks like

<ion-header>
  <ion-toolbar>
    <ion-title>
     List Wifi AP
    </ion-title>
  </ion-toolbar>
</ion-header>

<ion-content padding>

    <ion-button color="primary" (click)="getNetworks()">Get Networks</ion-button>
    {{info_txt}}
    <ion-list>
        <ion-item *ngFor="let data of results">
            {{data.SSID}} -
            {{data.BSSID}}
        </ion-item>
      </ion-list>
</ion-content>

Replace the content form the file src/app/home/home.page.ts so that is looks like

import { Component } from '@angular/core';

declare var WifiWizard2: any;

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage {
  results = [];
  info_txt = "";
  async getNetworks() {
    this.info_txt = "loading...";
    try {
      let results = await WifiWizard2.scan();
      this.results = results;
      this.info_txt = "";
    } catch (error) {
      this.info_txt = error;
    }
  }
}

Screenshots of the Wifi app

WifiWizard2 Empty list WifiWizard2 Scan Results