はじめに
Suicaやマイナンバーカードなど、
NFCとスマートフォンの連携が加速しているようです。
今回はReactNativeで、NFCの読み取りアプリの雛形を作成していきます。
ReactNativeプロジェクトの作成
まずはReactNativeのインストールから始めましょう。
アプリの名前はnfcappにしました。
npx react-native init nfcapp
NFCライブラリのインストール
今回はお手軽に、NFCを扱うライブラリをインストールして使用します。
https://github.com/whitedogg13/react-native-nfc-manager 📕
npm i --save react-native-nfc-manager
cd ios && pod install && cd ..
XCodeでCapabilityを追加
ワークスペースをXCodeで開き、Capabilityを追加します。
Signning & Capabilities -> + Capability -> Near Field Communication Tag Reading
を選択し追加します。
info.plistにNFCReaderUsageDescriptionを追加
iosディレクトリ内のinfo.plistにNFCReaderUsageDescriptionを追加します。
<key>NFCReaderUsageDescription</key>
<string>YOUR_PRIVACY_DESCRIPTION</string>
Build & Run
では、実機につないで起動しましょう。
無事に初期画面が表示されれば成功です。
サンプルコードを試す
App.jsをサンプルコードに書き換えて動作確認してみます。
サンプルコードは、ライブラリのREADMEにもリンクがあります。
https://github.com/whitedogg13/react-native-nfc-manager/blob/master/example/AppV2.js
App.js
import React from 'react';
import { View, Text, TouchableOpacity } from 'react-native';
import NfcManager, {NfcEvents} from 'react-native-nfc-manager';
class App extends React.Component {
  componentDidMount() {
    NfcManager.start();
    NfcManager.setEventListener(NfcEvents.DiscoverTag, tag => {
      console.warn('tag', tag);
      NfcManager.setAlertMessageIOS('I got your tag!');
      NfcManager.unregisterTagEvent().catch(() => 0);
    });
  }
  componentWillUnmount() {
    NfcManager.setEventListener(NfcEvents.DiscoverTag, null);
    NfcManager.unregisterTagEvent().catch(() => 0);
  }
  render() {
    return (
      <View style={{padding: 20}}>
        <Text>NFC Demo</Text>
        <TouchableOpacity
          style={{padding: 10, width: 200, margin: 20, borderWidth: 1, borderColor: 'black'}}
          onPress={this._test}
        >
          <Text>Test</Text>
        </TouchableOpacity>
        <TouchableOpacity
          style={{padding: 10, width: 200, margin: 20, borderWidth: 1, borderColor: 'black'}}
          onPress={this._cancel}
        >
          <Text>Cancel Test</Text>
        </TouchableOpacity>
      </View>
    );
  }
  _cancel = () => {
    NfcManager.unregisterTagEvent().catch(() => 0);
  };
  _test = async () => {
    try {
      await NfcManager.registerTagEvent();
    } catch (ex) {
      console.warn('ex', ex);
      NfcManager.unregisterTagEvent().catch(() => 0);
    }
  };
}
export default App;
NFCカードの読み取り
『TEST』『CANCEL』の2つのボタンが表示されているかと思います。
『TEST』ボタンを押下することで、NFCの読み取りが可能です。💳