⚡ Announcing the Capacitor NFC Plugin
Tags: javascript, webdev, ionic, capacitor
Published: 2022-08-17 10:59:08

Today I'm happy to introduce the brand new [Capacitor NFC](https://capawesome.io/plugins/nfc/) plugin from Capawesome, sponsored by [NFC21](https://nfc21.de/?_locale=en&utm_source=devto&utm_medium=referral&utm_campaign=capawesome).
This plugin enables interaction with Near Field Communication (NFC) tags and provides cross-platform support for Android, iOS, and Web. The project is available as Sponsorware on [GitHub](https://github.com/capawesome-team/capacitor-plugins).

Let's take a quick look at the [NFC plugin API](https://capawesome.io/plugins/nfc/#api) and how you can read and write on passive NFC tags and stickers. For this we will use the NTAG 215 from this [NFC Starter Kit](https://www.nfc-tag-shop.de/en/NFC-Starter-Kit-Medium-12-pieces/68250?utm_source=devto&utm_medium=referral&utm_campaign=capawesome).

## Installation

See [Getting started with Insiders](https://capawesome.io/insiders/getting-started/?plugin=capacitor-nfc) and follow the instructions to install the plugin.

After that, follow the platform-specific instructions in the sections [Android](#android) and [iOS](#ios).

### Android

The NFC API requires the following permissions be added to your `AndroidManifest.xml` before the `application` tag:

```xml
<uses-permission android:name="android.permission.NFC" />
<uses-sdk android:minSdkVersion="10"/>
```

### iOS

Make sure that the `Near Field Communication Tag Reading` capabilities have been enabled in your application in Xcode.
See [Add a capability to a target](https://help.apple.com/xcode/mac/current/#/dev88ff319e7) for more information.

Finally, add the `NFCReaderUsageDescription` key to the `ios/App/App/Info.plist` file, which tells the user why the app needs to use NFC:

```xml
<key>NFCReaderUsageDescription</key>
<string>The app enables the reading and writing of various NFC tags.</string>
```

## Usage

Now let's finally start and see the plugin in action.

### Read NFC tags

Reading NFC tags is quite simple: 

```typescript
import { Nfc } from '@capawesome-team/capacitor-nfc';

Nfc.addListener('nfcTagScanned', event => {
  console.log('NFC tag scanned: ', event.nfcTag);
});

await Nfc.startScanSession();
```

First you have to add the `nfcTagScanned` listener. This listener is called when an NFC tag is scanned as well as when an NFC tag opens your app. 
As soon as the listener is active, you can start a new scan session with [`Nfc.startScanSession(...)`](https://capawesome.io/plugins/nfc/#startscansession). During this session the operating system is looking for NFC tags.

### Write NFC tags

An NFC tag can contain different types of data in different formats such as **NDEF**. NDEF means **NFC Data Exchange Format** and defines in which format data is stored on NFC tags and in which way it can be read.

Here we create a simple NDEF text record using [`NfcUtils`](https://github.com/capawesome-team/capacitor-plugins/blob/main/packages/nfc/docs/utils/README.md), a utility class with various helper functions:

```typescript
import { NfcUtils } from '@capawesome-team/capacitor-nfc';

const utils = new NfcUtils();
const { record } = utils.createNdefTextRecord({ text: 'Capacitor NFC Plugin' });
```

This record can now be written to an NFC tag.
A NFC tag may be written to at the moment it is scanned.
That means we have to add the `nfcTagScanned` listener again.

```typescript
import { Nfc, NfcUtils } from '@capawesome-team/capacitor-nfc';

const utils = new NfcUtils();
const { record } = utils.createNdefTextRecord({ text: 'Capacitor NFC Plugin' });

Nfc.addListener('nfcTagScanned', event => {
  Nfc.write({ message: { records: [record] } });
});

await Nfc.startScanSession();
```

Now we can call [`Nfc.write(...)`](https://capawesome.io/plugins/nfc/#write) and write the record to the NFC tag while the tag is being scanned.

### Make NFC tags read-only

It is possible to make NFC tags permanently read-only using the [`makeReadOnly`](https://capawesome.io/plugins/nfc/#makereadonly) method:

```typescript
import { Nfc } from '@capawesome-team/capacitor-nfc';

Nfc.addListener('nfcTagScanned', event => {
  Nfc.makeReadOnly();
});

await Nfc.startScanSession();
```

⚠️ **Please take care**: This is a one-way operation and cannot be undone. Once an NFC tag has been made read-only, it can no longer be written to.

### Send custom commands to NFC tags

And finally, we can send custom commands to the NFC tag.
Which NFC tag supports which commands can be found in the respective specification of the tag.
The specification for NTAG 215 can be found [here](https://www.nxp.com/docs/en/data-sheet/NTAG213_215_216.pdf).  

ℹ️ Note that the codes in the specifications are often in hex format, but the plugin needs them as byte array.  

In the following example we read the signature of the tag:

```ts
import { Nfc } from '@capawesome-team/capacitor-nfc';

Nfc.addListener('nfcTagScanned', async (event) => {
  const { response } = await Nfc.transceive({ 
    techType: NfcTagTechType.NfcA, 
    data: [60, 0] 
  });
  return response;
});

await Nfc.startScanSession();
```

For this, we send the command (`[60, 0]`) to the tag using the [`Nfc.transceive(...)`](https://capawesome.io/plugins/nfc/#transceive) method and receive the signature as a byte array.

## Closing Thoughts

Be sure to check out our [API Reference](https://capawesome.io/plugins/nfc/) to see what else you can do with this plugin. Also feel free to take a look at our [demo app](https://github.com/capawesome-team/capacitor-nfc-demo) which shows this plugin in action.