> For AI agents: the complete documentation index is available at /llms.txt, the full documentation bundle is available at /llms-full.txt.

# LynxWifi

Reads the Wi-Fi network the phone is on, and joins another one. `import { LynxWifi } from '@blotch/angular-lynx';`

Setting up a smart device usually goes this way:

1. The app reads the phone's network, and asks the person for its password.
2. It sends both to the device, over Bluetooth or over the device's own access point, which the app joins first.

## Turn it on

Add `wifi` to the `build` target's options in angular.json, with the parts your app calls. To read the network, also add `permissions.location`, with the [reason](/guide/native-apps/permissions.md) iOS shows when it asks for the person's location:

```json title="angular.json"
"options": {
  "permissions": { "location": "Find your Wi-Fi network to set up the frame" },
  "wifi": { "join": true, "readCurrentNetwork": true }
}
```

What each part adds:

| Part                 | Methods             | iOS                                    | Android                                                          |
| -------------------- | ------------------- | -------------------------------------- | ---------------------------------------------------------------- |
| `join`               | `join()`, `leave()` | The Hotspot Configuration capability   | `CHANGE_WIFI_STATE`, `CHANGE_NETWORK_STATE`, `ACCESS_WIFI_STATE` |
| `readCurrentNetwork` | `currentNetwork()`  | The Access WiFi Information capability | `ACCESS_WIFI_STATE`, with `permissions.location`'s permissions   |

- **Android** grants the Wi-Fi and network permissions at install, and asks for the location ones. Wi-Fi is declared not required, so Google Play still offers the app to devices without it.
- **`readCurrentNetwork` needs `permissions.location` too,** and the build stops without it. Both platforms give the network's name only to an app with the person's location.

Without `wifi`, the native module is left out of both apps, and every method rejects with `unavailable`. A part you leave out is left out the same way: its native code isn't in either app, and its methods reject with `unavailable`.

:::warning A paid Apple team
A free Apple ID can't sign these capabilities. Each part adds an [entitlement](/guide/glossary.md#entitlement) to the iOS app: `com.apple.developer.networking.HotspotConfiguration` and `com.apple.developer.networking.wifi-info`.

Only a team in the paid Apple Developer Program can sign them for an iPhone, so ask only for the parts you call. The Simulator needs no team.
:::

See [Turn on device features](/guide/native-apps/device-features.md) for every setting.

## Usage

```typescript
import { Component, inject, signal } from '@angular/core';
import { LYNX_ELEMENTS, LynxWifi, WifiError } from '@blotch/angular-lynx';
import { Frame } from './frame';

@Component({
  selector: 'app-frame-setup',
  imports: [LYNX_ELEMENTS],
  template: `
    <input
      placeholder="Your Wi-Fi network"
      [value]="network()"
      (bindinput)="network.set($event.detail.value)"
    />
    <input
      placeholder="Its password"
      type="password"
      (bindinput)="password.set($event.detail.value)"
    />
    <view (bindtap)="connect('1234')"><text>Connect</text></view>
    <text>{{ status() }}</text>
  `,
})
export class FrameSetup {
  readonly #wifi = inject(LynxWifi);
  readonly #frame = inject(Frame);
  readonly network = signal('');
  readonly password = signal('');
  readonly status = signal('');

  async ngOnInit() {
    try {
      // On iOS, the first call asks for the person's location.
      this.network.set((await this.#wifi.currentNetwork())?.ssid ?? '');
    } catch (error) {
      // Let the person type the network's name instead.
      if (!(error instanceof WifiError)) throw error;
    }
  }

  async connect(code: string) {
    const frame = `Blotch-${code}`;
    try {
      // The frame's own access point, which has no internet.
      await this.#wifi.join({ ssid: frame, joinOnce: true });
      await this.#frame.sendNetwork(this.network(), this.password());
      this.status.set('The frame is joining your network');
    } catch (error) {
      if (error instanceof WifiError && error.code === 'notFound') {
        this.status.set('Is the frame switched on and close by?');
      } else {
        throw error;
      }
    } finally {
      await this.#wifi.leave(frame);
    }
  }
}
```

`Frame` stands for the app's own code that talks to the device, and `1234` for the code printed on it.

## API

### `LynxWifi`

```typescript
@Injectable({ providedIn: 'root' })
class LynxWifi {
  currentNetwork(): Promise<WifiNetwork | null>;
  join(options: WifiJoinOptions): Promise<void>;
  leave(ssid: string): Promise<void>;
}
```

| Platform                                          | `LynxWifi`                                                                                                |
| ------------------------------------------------- | --------------------------------------------------------------------------------------------------------- |
| iOS                                               | `NEHotspotNetwork` and `NEHotspotConfigurationManager`                                                    |
| Android                                           | `WifiManager`, `WifiNetworkSpecifier` and `WifiNetworkSuggestion`, from Android 10 for `join()`           |
| [Web preview](/guide/glossary.md#web-preview)     | Rejects with `unavailable`: a browser can't read or join a network                                        |
| Unit tests with the testing library               | What [`setWifiNetwork()`](/api/testing-library/fakes/connectivity.md#setwifinetwork) and its siblings set |
| [Lynx Explorer](/guide/glossary.md#lynx-explorer) | Rejects with `unavailable`                                                                                |

### `currentNetwork()`

Resolves the network the phone is on, `{ ssid, bssid? }`, or `null` when it isn't on Wi-Fi. The BSSID, the access point's hardware address, is in lowercase, and missing when the platform hides it.

- **iOS:** `NEHotspotNetwork.fetchCurrent`. The first call asks for the person's location, with `permissions.location`'s reason. iOS gives the network only with Precise Location on. It rejects with `denied` when the person says no.
- **Android:** `WifiManager`, once the app has `ACCESS_FINE_LOCATION` and Location is on. A call without the permission asks for the person's location first. Android 12 and later offer precise and approximate, and only precise gives the network's name.
- **`denied` on Android:** when the person refuses or picks approximate, and when Location is off. Android stops asking after the second refusal, and then only Settings can grant it ([`openAppSettings()`](/api/angular-lynx/sharing/linking.md#lynxlinkingopenappsettings) opens the app's page there). So let the person type the network's name when it's `denied`.

### `join(options)`

Joins the network. When it resolves depends on the platform and the options. Don't take it as proof the phone is on the network unless the list below says so:

- **iOS with `readCurrentNetwork`:** once the phone is on it.
- **iOS with `join` alone:** once the person allowed the network. iOS says nothing about whether the phone then joined it.
- **Android with `joinOnce`:** once the phone is on it.
- **Android without `joinOnce`:** once Android has the network, which the phone joins later, when it's in range.

It throws a `TypeError`, before asking anything, for a name longer than 32 bytes of UTF-8. It does the same for a password that isn't 8 to 63 printable ASCII characters.

| Option     | Type      | Means                                                                                                                                 |
| ---------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------- |
| `ssid`     | `string`  | The network's name                                                                                                                    |
| `password` | `string`  | Its WPA2 or WPA3 passphrase. Leave it out for an open network                                                                         |
| `joinOnce` | `boolean` | Whether the phone joins it only while the app uses it, rather than saving it, as for a device's own access point. Defaults to `false` |

**On iOS,** it uses `NEHotspotConfigurationManager`, after iOS asks the person whether the app may join the network.

- iOS answers that it joined even when the network is out of range. So with `readCurrentNetwork` too, `join()` reads the network afterwards, and rejects with `notFound` when the phone isn't on it.
- With `joinOnce`, iOS leaves the network once the app has been in the background a while.

**On Android 10 and later,** it depends on `joinOnce`. Earlier Android versions reject with `unavailable`.

- **With `joinOnce`:** a `WifiNetworkSpecifier`. Android shows a dialog where the person picks the network. The app's traffic then goes over it: a device's access point has no internet, so Android would otherwise keep the app on mobile data or another Wi-Fi. That includes the app's own `fetch()`, so call `leave()` once you're done with the device.
- **Without `joinOnce`:** a `WifiNetworkSuggestion`. The system adds it to the networks it joins by itself, the first time after the person allows the app's suggestions in a notification.

### `leave(ssid)`

Forgets a network `join()` joined, which takes the phone off it if it's on it. iOS removes the configuration. Android releases the network it asked for and removes its suggestion.

It resolves for a network the app didn't join too, which stays as it is.

### `WifiError`

Each method rejects with a `WifiError`, whose `code` says why:

| Code          | Means                                                                                                                              |
| ------------- | ---------------------------------------------------------------------------------------------------------------------------------- |
| `denied`      | The app may not read the network's name: no location permission, Precise Location or Location turned off                           |
| `notFound`    | The phone didn't join the network: it isn't in range, or the password is wrong. On Android, also when the person closed its dialog |
| `canceled`    | The person refused, in iOS's prompt or, for a suggestion, in Android's Settings                                                    |
| `unavailable` | The host can't: the part isn't in the app's `wifi`, `join()` before Android 10, the web preview or Lynx Explorer                   |
| `failed`      | The platform refused for another reason, given in the message                                                                      |

Android doesn't tell a closed dialog apart from a network the phone couldn't join.

## Testing

Each test's phone starts off Wi-Fi, so `currentNetwork()` resolves `null`. Every `join()` succeeds and puts the phone on the network, and `leave()` takes it off again.

- [`setWifiNetwork()`](/api/testing-library/fakes/connectivity.md#setwifinetwork) puts it on a network.
- [`denyWifiNetworkRead()`](/api/testing-library/fakes/connectivity.md#denywifinetworkread) makes `currentNetwork()` reject, as a phone whose owner refused the location does.
- [`queueWifiJoinResult()`](/api/testing-library/fakes/connectivity.md#queuewifijoinresult) answers the next `join()`.
- [`wifiJoins()`](/api/testing-library/fakes/connectivity.md#wifijoins) lists the joins.

```typescript
import {
  fireEvent,
  queueWifiJoinResult,
  render,
  screen,
  setWifiNetwork,
  waitForUpdate,
  wifiJoins,
} from '@blotch/angular-lynx-testing-library';

setWifiNetwork({ ssid: 'Home' });
queueWifiJoinResult('notFound');
await render(FrameSetup);
fireEvent.tap(screen.getByText('Connect'));
await waitForUpdate();
expect(wifiJoins()).toEqual([{ ssid: 'Blotch-1234', joinOnce: true }]);
expect(
  screen.getByText('Is the frame switched on and close by?'),
).toBeInTheDocument();
```

## Related

- [Turn on device features](/guide/native-apps/device-features.md): the `wifi` option and the other opt-in build options
- [Permission reasons](/guide/native-apps/permissions.md): the `location` reason
- [`LynxBluetooth`](/api/angular-lynx/hardware/bluetooth.md): send the network to a device over Bluetooth
