Giter VIP home page Giter VIP logo

react-native-nfc-manager's Introduction

react-native-nfc-manager

npm version build issues

Bring NFC feature to React Native. Inspired by phonegap-nfc and react-native-ble-manager

Contributions are welcome!

Made with ❤️ by whitedogg13 and revteltech

Special thanks to javix64 for restructuring the documentation!

Table of Contents

  1. Installation
  2. Getting Started
  3. Setup
  4. Documentation
  5. Nfc compatibility
  6. Usage Concept
  7. API
  8. App demo
  9. Learn

Installation

npm i --save react-native-nfc-manager

iOS

This library use native-modules, so you will need to do pod install for iOS:

cd ios && pod install && cd ..

Android

It should be properly auto-linked, so you don't need to do anything.

Setup

iOS

  1. In apple developer site, enable capability for NFC

enable capability

  1. in Xcode, add NFCReaderUsageDescription into your info.plist, for example:
<key>NFCReaderUsageDescription</key>
<string>We need to use NFC</string>

More info on Apple's doc

Additionally, if writing ISO7816 tags add application identifiers (aid) into your info.plist as needed like this.

<key>com.apple.developer.nfc.readersession.iso7816.select-identifiers</key>
<array>
  <string>D2760000850100</string>
  <string>D2760000850101</string>
</array>

More info on Apple's doc

Note: If you are using NfcTech.FelicaIOS, you must also add the following code to your Info.plist file, otherwise the library will crash:

<key>com.apple.developer.nfc.readersession.felica.systemcodes</key>
<array>
  <string>8005</string>
  <string>8008</string>
  <string>0003</string>
  <string>fe00</string>
  <string>90b7</string>
  <string>927a</string>
  <string>12FC</string>
  <string>86a7</string>
</array>

An incomplete list of aid's can be found here. Application identifier

  1. in Xcode's Signing & Capabilities tab, make sure Near Field Communication Tag Reading capability had been added, like this:

xcode-add-capability

If this is the first time you toggle the capabilities, the Xcode will generate a <your-project>.entitlement file for you:

xcode-add-entitlement

  1. in Xcode, review the generated entitlement. It should look like this:

edit entitlement

More info on Apple's doc

Android

Simple add uses-permission into your AndroidManifest.xml:

 <uses-permission android:name="android.permission.NFC" />

Support Android 12

We start to support Android 12 from v3.11.1, and you will need to update compileSdkVersion to 31, otherwise the build will fail:

buildscript {
    ext {
        ...
        compileSdkVersion = 31
        ...
    }
    ...
}

The reason for this is because Android puts new limitation on PendingIntent which says Starting with Build.VERSION_CODES.S, it will be required to explicitly specify the mutability of PendingIntents

The original issue is here

If you don't care about Android 12 for now, you can use v3.11.0 as a short term solution.

Getting Started

The simplest (and most common) use case for this library is to read NFC tags containing NDEF, which can be achieved via the following codes:

import React from 'react';
import {View, Text, TouchableOpacity, StyleSheet} from 'react-native';
import NfcManager, {NfcTech} from 'react-native-nfc-manager';

// Pre-step, call this before any NFC operations
NfcManager.start();

function App() {
  async function readNdef() {
    try {
      // register for the NFC tag with NDEF in it
      await NfcManager.requestTechnology(NfcTech.Ndef);
      // the resolved tag object will contain `ndefMessage` property
      const tag = await NfcManager.getTag();
      console.warn('Tag found', tag);
    } catch (ex) {
      console.warn('Oops!', ex);
    } finally {
      // stop the nfc scanning
      NfcManager.cancelTechnologyRequest();
    }
  }

  return (
    <View style={styles.wrapper}>
      <TouchableOpacity onPress={readNdef}>
        <Text>Scan a Tag</Text>
      </TouchableOpacity>
    </View>
  );
}

const styles = StyleSheet.create({
  wrapper: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
});

export default App;

DOCUMENTATION

Check the full documentation that contains examples, faq and other topics like Expo in our Wiki

Nfc Compatibility

NFC Technologies Android iOS
Ndef
NfcA
IsoDep
NfcB
NfcF
NfcV
MifareClassic
MifareUltralight
MifareIOS
Iso15693IOS
FelicaIOS

Usage concept

In higher level, there're 4 steps to use this library:

  1. (Recommended but not necessary) Before all next steps, use NfcManager.start() to start listen a tag.

  2. Request your particular NFC technologies through NfcManager.requestTechnology. Let's request Ndef techonogy.

NfcManager.requestTechnology(NfcTech.Ndef);
  1. Select the proper NFC technology handler, which is implemented as getter in main NfcManager object.
NfcManager.ndefHandler
  1. Call specific methods on the NFC technology handler.
NfcManager.ndefHandler.getNdefMessage()
  1. Clean up your tech registration through:
NfcManager.cancelTechnologyRequest()

API

The following table shows the handler for each technology, so if you need to use a technology, go to index.d.ts and search for it.

NFC Technologies Handlers
Ndef NdefHandler
NfcA NfcAHandler
IsoDep IsoDepHandler
NfcB -
NfcF -
NfcV NfcVHandler
MifareClassic MifareClassicHandlerAndroid
MifareUltralight MifareUltralightHandlerAndroid
MifareIOS -
Iso15693IOS Iso15693HandlerIOS
FelicaIOS -

App Demo - NfcOpenReWriter

We have a full featured NFC utility app using this library available for download. The source code is here: React Native NFC ReWriter App

react-native-nfc-rewriter
react-native-nfc-rewriter

Learn

We have published a React Native NFC course with newline.co, check it out!

  • Free course (1 hour) about basic NFC setup and concept here
  • Full course (3 hours) for more (NDEF, Deep Linking, NTAG password protection, signature with UID) here

react-native-nfc-manager's People

Contributors

acasademont avatar april-ayres avatar changtimwu avatar christianchown avatar christophebelpaire avatar clickclickonsal avatar clrsustainas avatar dependabot[bot] avatar dylanclements avatar evanbacon avatar frans-l avatar guck111 avatar hblab-nghianh avatar javix64 avatar jlkalberer avatar linmic avatar matzielab avatar mharj avatar mhdstk avatar moony-chen avatar nicholasbertazzon avatar pedroyan avatar poison avatar rrrasti avatar spedy avatar storm2513 avatar symous avatar vishaljak avatar whitedogg13 avatar zamfi99 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-native-nfc-manager's Issues

Formatting NdefFormatable NFC tags

Hi,

I've been using your javascript library to make a basic NFC read/write app and it has worked well up untill now. My issue is that I need to format the tags to Ndef from NdefFormatable. Your library doesn't supply functions for this and the only alternative is porting a massive java library from chariotsolution's Phone-gap, which is not possible in my amount of given time (and skill).

Could you supply a method for formatting the tags to Ndef? Or give a reasoning I need to follow in order to code it myself.

Thanks

NfcManager.start doesn't properly remove the iOS event listener.

I created an NFC Screen & I've decided to initialize the NFC when I navigate to it. In my componentDidMount function I have the code shown below.

componentDidMount = () => {
    NfcManager.start({
      onSessionClosedIOS: () => {
          console.log('session closed');
          this._stopDetection();
          this.props.navigation.goBack();
       },
    });
};

This works just fine the first time around. I'll navigate to the screen, then on cancel it'll take me back, then I'll navigate to the screen again & when I click cancel I get the following error message.
image

I took a look at the source code & found that the issue is that Events.SessionClosed event listener is being removed properly. So I've submitted a pull request #8 with a fix for this. :-)

Attempt to get length of null array on NfcManager.start()

Hi,

When I run NfcManager.start(), an error occurs saying "Attempt to get length of null array" and pointing to your NfcManager.java line 70. It indicates that invoke function does not accept null param. FYI, I tested on multiple Android devices, with and without a callback function as NfcManager.start() param.

So, I changed NfcManager.java line 70 callback.invoke param to a string and it works (callback.invoke("null"); instead of callback.invoke(null);). I know that it is not a solution at all, so I just notice you about it because I don't have time to fix it and to send you a pull request.

Regards.

using nfc with android

Hello,
I'm trying to use in nfc with phone that support it. what I did it

` componentDidMount() {
console.log('props scanpage', this.props);

    NfcManager.isSupported()
    .then(supported => {
        this.setState({ supported });
        if (supported) {
            this._startNfc();
        }
    })
}

_startNfc() {
    NfcManager.start({
        onSessionClosedIOS: () => {
            console.log('ios session closed');
        }
    }).then(result => {
        console.log(result)
        this.setState({ nfcSupport: true })
    }).catch(err => {
        this.setState({ nfcSupport: false })

    })
    if (Platform.OS === 'android'){
        NfcManager.registerTagEvent(tag => {
            console.log('Tag Discovered', tag);
        }, 'Hold your device over the tag', true)
        NfcManager.isEnabled()
        .then(enabled => {
            console.log(enabled)
            this.setState({ nfcSupport: enabled ? true : false, nfcAllow: enabled ? true : false })

        })
        .catch(err => {
            console.log(err);
        })
    }`

but I don't see any response or any listener change when the nfc is work.
in ios it's works fine.

TypeError undefined is not an object

Hi there,
I was trying to implement this package on my react-native project, but when I try to reference the functions from the NFCManager from react-native-nfc-manager, all the functions catch error instead of going to .then.

"react-native": "^0.47.0",:
"react": "^16.0.0-alpha.12",

Android Device:
Android Version: 7.1.1

I did the following setting steps:
npm install -s react-native-nfc-manager
react-native link react-native-nfc-manager

I try to print its error message, it says:
you could ignore the string start, the start is hard code. 😂
screenshot_2018-05-03-10-28-24

Is there any steps that I missing? Thx~

ios build failed

...node_modules/react-native/React/Base/RCTBundleURLProvider.m:17:53: error: use of undeclared identifier 'undefined'; did you mean 'underline'?
const NSUInteger kRCTBundleURLProviderDefaultPort = RCT_METRO_PORT;
                                                    ^~~~~~~~~~~~~~
                                                    underline
In file included from <built-in>:359:
<command line>:5:24: note: expanded from here
#define RCT_METRO_PORT undefined
                       ^
In module 'Darwin' imported from...

Unable To write Plain text

Need Help to write plain text. Is there any option where we can right plain text. Right now whatever we write is saved as URL.

Thanks in Advance !

NfcManager.registerTagEvent got 1 arguments, expected 3

from code
_startDetection = () => { NfcManager.registerTagEvent(tag => { console.log('Tag Discovered', tag); }, 'Hold your device over the tag', true) };

debug error:
NfcManager.registerTagEvent got 1 arguments, expected 3

com.facebook.react.bridge.JavaMethodWrapper.invoke JavaMethodWrapper.java:344 com.facebook.react.bridge.JavaModuleWrapper.invoke JavaModuleWrapper.java:166 com.facebook.react.bridge.queue.NativeRunnable.run NativeRunnable.java android.os.Handler.handleCallback Handler.java:739 android.os.Handler.dispatchMessage Handler.java:95 com.facebook.react.bridge.queue.MessageQueueThreadHandler.dispatchMessage MessageQueueThreadHandler.java:31 android.os.Looper.loop Looper.java:155 com.facebook.react.bridge.queue.MessageQueueThreadImpl$3.run MessageQueueThreadImpl.java:194 java.lang.Thread.run Thread.java:818

SDK:27
BuildTool: 27.0.2
React native: 0.46.4
"react-native-nfc-manager": "0.1.0",

package community.revteltech.nfc does not exist

I got this error after install and link the module, please help 😢

Task :app:compileDebugJavaWithJavac
C:\Users\myers\Desktop\movifree\android\app\src\main\java\com\movifree\MainApplication.java:6: error: package community.revteltech.nfc does not exist
import community.revteltech.nfc.NfcManagerPackage;
^
C:\Users\myers\Desktop\movifree\android\app\src\main\java\com\movifree\MainApplication.java:29: error: cannot find symbol
new NfcManagerPackage(),
^
symbol: class NfcManagerPackage
2 errors

FAILURE: Build failed with an exception.

my package.json

"dependencies": {
"react": "16.3.1",
"react-native": "0.55.4",
"react-native-camera": "^1.1.4",
"react-native-nfc-manager": "^0.5.0",
"react-native-qrcode-scanner": "^1.0.1",
"react-navigation": "^2.3.1",
"react-redux": "^5.0.7",
"redux": "^4.0.0",
"redux-logger": "^3.0.6"
},

Not able to scan tag again after canceling on ios.

I am trying to read nfc tag on ios. If i cancel scanning from popup then i am not able to scan tag again.
I have to again navigate to screen again to start detecting scan again. It's working fine on android.

39761313-13dd273c-52d8-11e8-913f-5c0bcb8e5a57

How do I get the data of NFC card?

Currently I just get this tag info:

Object {
  "id": Array [
    4,
    109,
    -123,
    10,
    116,
    76,
    -127,
  ],
  "maxSize": 142,
  "ndefMessage": Array [
    Object {
      "id": Array [],
      "payload": Array [
        1,
        101,
        98,
        115,
        108,
        46,
        104,
        107,
      ],
      "tnf": 1,
      "type": Array [
        85,
      ],
    },
  ],
  "techTypes": Array [
    "android.nfc.tech.NfcA",
    "android.nfc.tech.MifareUltralight",
    "android.nfc.tech.Ndef",
  ],
  "type": "NFC Forum Type 2",
}

How do I get the stored data from NFC card?

NfcManager.requestNdefWrite(bytes) not resolving promise successfully or catching error (until NfcManager.cancelNdefWrite())

When I call NfcManager.requestNdefWrite(bytes) the promise never resolves nor is an error ever caught. It just fires off the request and waits as though it's taking forever to write the Ndef. Is this the expected behavior?

I imagine that it should complete immediately after requesting a write. Am I understanding this correctly, that NfcManager.requestNdefWrite(bytes) is creating the "radio wave" output of the bytes input, and once that process is completed successfully it should log "write completed"? If that is the case, can someone please point out the reason why this output is not generated?

  _startDetection = () => {
    NfcManager.registerTagEvent(this._onTagDiscovered)
    .then(result => {
        console.log('registerTagEvent OK', result)
        // Make sure I register tag event first
        if (Platform.OS === 'android') this._requestNdefWrite();
    })
    .catch(error => {
        console.warn('registerTagEvent fail', error)
    })
  }



  _requestNdefWrite = () => {
    function strToBytes(str) {
        let result = [];
        for (let i = 0; i < str.length; i++) {
          result.push(str.charCodeAt(i));
        }
      return result;
    }

    let { isWriting } = this.state;
    if (isWriting) {
        return;
    }

    const urlBytes = strToBytes('https://google.com');
    const headerBytes = [0xD1, 0x01, (urlBytes.length + 1), 0x55, 0x01];
    const bytes = [...headerBytes, ...urlBytes];

    this.setState({isWriting: true});
    NfcManager.requestNdefWrite(bytes)
      .then(() => console.log('write completed')) // Doesn't ever complete!
      .catch(err => console.warn(err)) // Logs "cancelled" after calling NfcManager.cancelNdefWrite()
      .then(() => {
        this.setState({isWriting: false})
        console.log('set state writing false') // Logs after calling NfcManager.cancelNdefWrite()
      });
  }



  _stopDetection = () => {
    NfcManager.unregisterTagEvent()
    .then(result => {
        console.log('unregisterTagEvent OK', result)
        NfcManager.stop();
        if (Platform.OS === 'android') NfcManager.cancelNdefWrite();
    })
    .catch(error => {
        console.warn('unregisterTagEvent fail', error)
    })
  }

getNdefMessage is not work

hi,
I copy the codes of AndroidTechTestNdef.js to my propject. but there are something wrong .

first time i detect the card , i get a warning of 'fail to connect tag'

second time i get the tag, its a object combine with id&&techType, but the getNdefMessage is also cant work.

Do I need to do some configuration in AndroidManifest.xml?


"react-native": "0.55.4",
"react-native-nfc-manager": "0.5.0"

thx

Feature Request: Add Support for Writing Tags (Android only)

I would like to be able to write, in addition to read, some basic tags from an Android phone (my understanding is such actions are not currently permitted on iOS.) Is there any plan to implement this? I wish I could help but my Android/java is lacking.

(Edit: I do notice that phonegap-nfc supports it so maybe I'll take a look at porting it.)

NFC permission required even when set to not required in AndroidManifest.xml

Hi There,

After adding this module, we now have 14k unsupported devices because of the NFC requirement. I have tried adding the required false to the uses-permission in the android manifest, but it seems like it somehow gets overwritten?

We have wrapped the plugin so we only serve the function with the plugin if the device has NFC but still Play console deems it unsupported for devices without NFC.

<uses-permission android:name="android.permission.NFC" android:required="false" />

screen shot 2017-12-08 at 09 41 36

Any ideas?

Url is sent through requestNdefWrite() but isn't received by the listening device. The listening device receives a payload that isn't the url.

Edit:
After further testing with another device, i'm able to receive a payload that isnt pointing to the google store. This means that the example app is receiving the payloads correctly and that my issue is with sending the NDEF message from the example app to another device.

        // <-- urlToWrite is the url entered by the user into the textinput 
        const urlBytes = strToBytes(urlToWrite); 
        const headerBytes = [0xD1, 0x01, (urlBytes.length + 1), 0x55, 0x01];
        const bytes = [...headerBytes, ...urlBytes];
        console.log("bytes");console.log(bytes)
        this.setState({isWriting: true});

        NfcManager.requestNdefWrite(bytes)
            .then(() => console.log('write completed'))
            .catch(err => console.warn(err))
            .then(() => this.setState({isWriting: false}));
    }

I have successfully built/launched the app for android that was in the examples folder. I'm writing successfully to another device (which is also running the example) so i know the tag was sent. The problem is the payload is always http://play.google.com/store/apps/details?id=[sending app name]&feature=beam

The below console output is from the onTagDiscovered() method where i have also added some extra console.log lines to get more info. There are only 2 ndefmessages no matter what i do and neither contain what i was expecting (ie google.com). I thought there might be an error in the payload that was being sent out but when I tried using another nfc app (called NFC Tools) to send a URI that was reddit.com the result was the same. http://play.google.com/store/apps/details?id=[sending app name]&feature=beam.

Shouldn't the payload contain the info that i'm sending?

image

failed to getting started on android

I just started with an empty react-native project "react-native init..."
Any advice?

FAILURE: Build failed with an exception.

* What went wrong:
A problem occurred configuring project ':app'.
> Could not resolve all dependencies for configuration ':app:_debugApk'.
   > A problem occurred configuring project ':react-native-nfc-manager'.
      > Could not resolve all dependencies for configuration ':react-native-nfc-manager:classpath'.
         > Could not download gradle-core.jar (com.android.tools.build:gradle-core:1.5.0)
            > Could not get resource 'https://jcenter.bintray.com/com/android/tools/build/gradle-core/1.5.0/gradle-core-1.5.0.jar'.
               > Could not HEAD 'https://jcenter.bintray.com/com/android/tools/build/gradle-core/1.5.0/gradle-core-1.5.0.jar'. Received status code 502 from server: Bad Gateway

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED

Total time: 20.305 secs
Could not install the app on the device, read the error above for details.
Make sure you have an Android emulator running or a device connected and have
set up your Android development environment:
https://facebook.github.io/react-native/docs/getting-started.html

with React Navigation

HomeScreen: read nfc tag
_onTagDiscovered = tag => {
try {
let url = this._parseUri(tag);
if (url) {
let nodeID = url.split('/');
this.props.navigation.navigate("ScreenB", {nodeID: nodeID[nodeID.length - 1]});
}
} catch (error) {
}
};

it reads fine and propagates to next screen until app goes in background and return to the foreground(android). Suppose I press back button and app goes in the background. when I reopen the app it reads well but can't propagate to the next screen.

Warning I am getting: can only update a mounted or mounting components. This usually means you called setState, replaceState or forceUpdate .....

any issue with react navigation or nfc manager?

Btw thanks for your effort. any suggestion is welcomed :)

Error: Couldn't find preset "env" relative to directory...

Hi,
I am trying to test your example then I got this build error:

error: bundling failed: Error: Couldn't find preset "env" relative to directory "/home/yuqi/code/react-native/Genu9/clients/react-native/node_modules/react-native-nfc-manager" at /home/yuqi/code/react-native/Genu9/clients/react-native/node_modules/babel-core/lib/transformation/file/options/option-manager.js:293:19 at Array.map (native) at OptionManager.resolvePresets (/home/yuqi/code/react-native/Genu9/clients/react-native/node_modules/babel-core/lib/transformation/file/options/option-manager.js:275:20) at OptionManager.mergePresets (/home/yuqi/code/react-native/Genu9/clients/react-native/node_modules/babel-core/lib/transformation/file/options/option-manager.js:264:10) at OptionManager.mergeOptions (/home/yuqi/code/react-native/Genu9/clients/react-native/node_modules/babel-core/lib/transformation/file/options/option-manager.js:249:14) at OptionManager.init (/home/yuqi/code/react-native/Genu9/clients/react-native/node_modules/babel-core/lib/transformation/file/options/option-manager.js:368:12) at File.initOptions (/home/yuqi/code/react-native/Genu9/clients/react-native/node_modules/babel-core/lib/transformation/file/index.js:212:65) at new File (/home/yuqi/code/react-native/Genu9/clients/react-native/node_modules/babel-core/lib/transformation/file/index.js:135:24) at Pipeline.transform (/home/yuqi/code/react-native/Genu9/clients/react-native/node_modules/babel-core/lib/transformation/pipeline.js:46:16)

I did npm i --save react-native-nfc-managerand react-native link react-native-nfc-manager successfully, but I didn't include pod 'react-native-nfc-manager', :path => '../node_modules/react-native-nfc-manager/' into the Podfile, because I can't find where it is. Does this Podfile have anything to do with the build error?

Thank you and forgive me if I ask a stupid question...

undefined is not an object (evaluating 'NativeNfcManager.registerTagEvent')

I'm getting this error when trying to use this on a Google Pixel (1st generation regular, not XL). NFC is enabled on my phone; when I open the app, I get the below error.

[Unhandled promise rejection: TypeError: undefined is not an object (evaluating 'NativeNfcManager.isSupported')]
- node_modules/react-native-nfc-manager/NfcManager.js:95:6 in <unknown>
- node_modules/promise/setimmediate/core.js:45:7 in tryCallTwo
- node_modules/promise/setimmediate/core.js:200:23 in doResolve
- node_modules/promise/setimmediate/core.js:66:12 in Promise
- node_modules/react-native-nfc-manager/NfcManager.js:96:8 in isSupported
* null:null in componentDidMount
- node_modules/react-proxy/modules/createPrototypeProxy.js:61:45 in proxiedComponentDidMount
- node_modules/react-native/Libraries/Renderer/ReactNativeRenderer-dev.js:8979:12 in commitLifeCycles
- ... 22 more stack frames from framework internals

When I click "Start Tag Detection" I get a similar error:

10:50:34: undefined is not an object (evaluating 'NativeNfcManager.requestNdefWrite')
- node_modules/react-native-nfc-manager/NfcManager.js:41:3 in <unknown>
- node_modules/promise/setimmediate/core.js:45:7 in tryCallTwo
- node_modules/promise/setimmediate/core.js:200:23 in doResolve
- node_modules/promise/setimmediate/core.js:66:12 in Promise
- node_modules/react-native-nfc-manager/NfcManager.js:32:4 in requestNdefWrite
* App.js:136:29 in _requestNdefWrite
- node_modules/react-native/Libraries/Components/Touchable/TouchableOpacity.js:199:45 in touchableHandlePress
- node_modules/react-native/Libraries/Components/Touchable/Touchable.js:746:34 in _performSideEffectsForTransition
- ... 23 more stack frames from framework internals

Does that mean this package and my device are incompatible? I am attaching my package.json file to see if there are any problems with my setup that might stop this from working.

{
  "name": "nfctest",
  "version": "0.1.0",
  "private": true,
  "devDependencies": {
    "jest-expo": "25.0.0",
    "react-native-scripts": "1.11.1",
    "react-test-renderer": "16.2.0"
  },
  "main": "./node_modules/react-native-scripts/build/bin/crna-entry.js",
  "scripts": {
    "start": "react-native-scripts start",
    "eject": "react-native-scripts eject",
    "android": "react-native-scripts android",
    "ios": "react-native-scripts ios",
    "test": "node node_modules/jest/bin/jest.js"
  },
  "jest": {
    "preset": "jest-expo"
  },
  "dependencies": {
    "expo": "^25.0.0",
    "react": "16.2.0",
    "react-native": "0.52.0",
    "react-native-nfc-manager": "^0.3.1"
  }
}

iOS saying NFC not supported

Issue

I have installed react-native-nfc-manager in my app and it works perfectly on Android but not on my iPhone 8.

Note: This is my first time using a react-native link'ed module.

Code

NfcManager.start({
  onSessionClosedIOS: () => {
    console.log('ios session closed')
  },
})
  .then(result => {
    console.warn('start OK', result)
  })
  .catch(error => {
    console.warn('device does not support nfc!')
  })

NfcManager.registerTagEvent(
  tag => {
    // console.warn('Tag Discovered', tag)
    // console.warn(JSON.stringify(tag, null, 2))
    // console.warn(tag.ndefMessage[0])
    console.warn(NdefParser.parseText(tag.ndefMessage[0]))
  },
  'Hold your device over the tag',
  true
)

Current Behavior

Android

Warning of start OK undefined. When scanning an NDEF NFC card, I get the message that's encoded. In other words, the line of console.warn(NdefParser.parseText(tag.ndefMessage[0])) prints out the message I want.

iOS

Warning of device does not support nfc!. Another warning of

Sending `NfcManagerSessionClosed` with no listeners registered.

Expected Behavior

Both to behavior like Android's current behavior listed above.

Theories

  • I didn't do the Podfile installation process because I thought the react-native link would do it under-the-hood
  • I didn't do anything regarding NFC permissions with Xcode

Error: Redefinition of RCTMethodInfo after installing the plugin

Hello,
I opened a new react-native project (latest version V0.49) and after installing the plugin react-nfc-manager,
I'm trying to run on ios with XCode 9 (simulators I test:IPHONE 6,7,7s IOS 11) it failed with error:

31434970-ade863a6-ae86-11e7-8e20-d6fec8d1df00

when I run on android it works fine.

Can't write NFC TAG - message "you should requestTagEvent first"

Hi, i can read the tag properly, but i can't write.
It appear a warning "you should requestTagEvent first"

I'm using your APP as example to test before i make my app implementation.

I have my Huawei P8 connected as emulator.

If you need more information, let me know.

Thank you

API to get UID

Issue

I can't access the meta info for the tag, such as UID.

Code

NfcManager.registerTagEvent(
  tag => {
    console.warn(tag)
  },
  'Hold your device over the tag',
  true
)

Current Behavior

iOS & Android

The tag returned does not include any information about the id. tag.ndefMessage[0].id exists but is an empty array.

Expected Behavior

Either tag.ndefMessage[0].id returns the UID or tag.uid returns the UID.

Theories

None

How to get NFC tag id on iOS

Hi,awesome lib(碉堡了,老哥)!

I have successfully scan a NFC with this lib on iPhone, but I can not find out the tag id(which can be find on Android). Is there any way we can get the that on iOS? thanks! :D

ios session closed in iphone 7

Hello,
i'm trying to implement this plugin into my code and run nfc but I get these lines in console log

`registerTagEvent OK undefined
ios sessionClosed`

when I run the startDetection manually I get also the same issues..
part of my code

`import { calcSize } from '../../utillities/utilites';
const { height, width } = Dimensions.get('window');

import NfcManager, { NdefParser } from 'react-native-nfc-manager';

export default class NfcScan extends Component {
    constructor(props) {
        super(props);
        this.state = {
            supported: true,
            enabled: false,
            tag: {},
            spinValue: new Animated.Value(0),
            opacityAnimate: new Animated.Value(1),
            width: new Animated.Value(calcSize(197)),
            nfcDetection: false
        }
    }

    componentDidMount() {
        // StatusBar.setHidden(true);

        NfcManager.start({
            onSessionClosedIOS: () => {
                console.log('ios session closed');
            }
        }).then(result => {
                if(!result){
                    console.log("not nfc detected");
                }else
                    console.log('start OK', result);
            })
            .catch(error => {
                console.warn('start fail', error);
                this.setState({supported: false});
            })

        if (Platform.OS === 'android') {
            NfcManager.getLaunchTagEvent()
                .then(tag => {
                    console.log('launch tag', tag);
                    if (tag) {
                        console.log(tag);
                        this.setState({ tag });
                    }
                })
                .catch(err => {
                    console.log(err);
                })
            NfcManager.isEnabled()
                .then(enabled => {
                    console.log(enabled);
                    this.setState({ enabled });
                })
                .catch(err => {
                    console.log(err);
                })
        }
    }`

App crash with Null pointer Exception when press start Tag detection in example

Hi,
I have followed the Readme and trying the example.
The example screen showing however the app crashed after i pressed start tag detection
screenshot_2018-04-12-11-44-08

My environment:

environment:
 OS:  Android 4.2.1
Packages: (installed)
  react: 16.3.0-alpha.1
  react-native: 0.54.3
  react-native-nfc-manager: ^0.3.2

Logcat in android studio:

E/AndroidRuntime: FATAL EXCEPTION: mqt_native_modules
    java.lang.NullPointerException
        at java.lang.AbstractStringBuilder.<init>(AbstractStringBuilder.java:86)
        at java.lang.StringBuilder.<init>(StringBuilder.java:95)
        at com.facebook.react.devsupport.DevSupportManagerImpl$JSExceptionLogger.log(DevSupportManagerImpl.java:303)
        at com.facebook.react.devsupport.DevSupportManagerImpl.handleException(DevSupportManagerImpl.java:287)
        at com.facebook.react.bridge.CatalystInstanceImpl.onNativeException(CatalystInstanceImpl.java:501)
        at com.facebook.react.bridge.CatalystInstanceImpl.access$900(CatalystInstanceImpl.java:40)
        at com.facebook.react.bridge.CatalystInstanceImpl$NativeExceptionHandler.handleException(CatalystInstanceImpl.java:517)
        at com.facebook.react.bridge.queue.MessageQueueThreadHandler.dispatchMessage(MessageQueueThreadHandler.java:33)
        at android.os.Looper.loop(Looper.java:137)
        at com.facebook.react.bridge.queue.MessageQueueThreadImpl$3.run(MessageQueueThreadImpl.java:194)
        at java.lang.Thread.run(Thread.java:856)

Would you please let me know how to fix the issue. Thank you.

Execution failed for task ':react-native-nfc:compileReleaseJavaWithJavac'.

react-native-nfc:preBuild UP-TO-DATE
:react-native-nfc:preReleaseBuild UP-TO-DATE
:react-native-nfc:checkReleaseManifest
:react-native-nfc:preDebugAndroidTestBuild UP-TO-DATE
:react-native-nfc:preDebugBuild UP-TO-DATE
:react-native-nfc:preDebugUnitTestBuild UP-TO-DATE
:react-native-nfc:preReleaseUnitTestBuild UP-TO-DATE
:react-native-nfc:prepareComAndroidSupportAppcompatV72301Library
:react-native-nfc:prepareComAndroidSupportSupportV42301Library
:react-native-nfc:prepareComFacebookFbuiTextlayoutbuilderTextlayoutbuilder100Library
:react-native-nfc:prepareComFacebookFrescoDrawee130Library
:react-native-nfc:prepareComFacebookFrescoFbcore130Library
:react-native-nfc:prepareComFacebookFrescoFresco130Library
:react-native-nfc:prepareComFacebookFrescoImagepipeline130Library
:react-native-nfc:prepareComFacebookFrescoImagepipelineBase130Library
:react-native-nfc:prepareComFacebookFrescoImagepipelineOkhttp3130Library
:react-native-nfc:prepareComFacebookReactReactNative0504Library
:react-native-nfc:prepareComFacebookSoloaderSoloader010Library
:react-native-nfc:prepareOrgWebkitAndroidJscR174650Library
:react-native-nfc:prepareReleaseDependencies
:react-native-nfc:compileReleaseAidl
:react-native-nfc:compileReleaseNdk UP-TO-DATE
:react-native-nfc:compileLint
:react-native-nfc:copyReleaseLint UP-TO-DATE
:react-native-nfc:compileReleaseRenderscript
:react-native-nfc:generateReleaseBuildConfig
:react-native-nfc:generateReleaseResValues
:react-native-nfc:generateReleaseResources
:react-native-nfc:mergeReleaseResources
:react-native-nfc:processReleaseManifest
:react-native-nfc:processReleaseResources
:react-native-nfc:generateReleaseSources
:react-native-nfc:incrementalReleaseJavaCompilationSafeguard UP-TO-DATE
:react-native-nfc:compileReleaseJavaWithJavac
:react-native-nfc:compileReleaseJavaWithJavac - is not incremental (e.g. outputs have changed, no previous execution, etc.).
D:\ProjectDirectory\node_modules\react-native-nfc\android\src\main\java\com\novadart\reactnativenfc\ReactNativeNFCPackage.java:21: error: method does not override or implement a method from a supertype
    @Override
    ^
1 error
:react-native-nfc:compileReleaseJavaWithJavac FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':react-native-nfc:compileReleaseJavaWithJavac'.
> Compilation failed; see the compiler error output for details.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED

I tried with yarn and npm install both but facing the same issue.

iPhone implementation crashing

Hello. I've setup my code based on the provided example. Im running the app on my iPhone 7+ and followed the instructions on the video. But when I trigger _startTrigger the app crashes and I cant seem to find an error. Any help would be greatly appreciated.

NfcManager.start return result 'undefined' always

Hello,
I installed the latest version you just published and I get result 'undefined' in any case I checked.
with undefined, I can't really check if the phone support in nfc or not, I don't have any indication to know..

Re-prompting on iOS

Issue

I have the library installed and working on iOS. I have set a button to run NfcManager.start() which opens the iOS prompt to scan the device. When pressing the button the first time, the prompt shows up. When pressing cancel then the button a second time, nothing shows up.

Code

const handleOnPress = () => {
  console.warn('pressed')

  NfcManager.start()

  const { sendReading } = this.props
  NfcManager.registerTagEvent(
    tag => {
      const reading = NdefParser.parseText(tag.ndefMessage[0])
      sendReading(reading)
    },
    'Hold your device over the tag',
    true
  )
}

Current Behavior

iOS

Prompt not showing up a second time when the button is tapped.

Android

Works perfectly. This is because it's an "always-on" state, rather than requiring a button to toggle a prompt.

Expected Behavior

After tapping the button a second time, I expected the prompt to show up again.

Theories

  • Need to call stop() when it is closed and restart it. This didn't work. See code below.
const handleOnPress = () => {
  console.warn('pressed')

  NfcManager.start({
    onSessionClosedIOS: () => {
      NfcManager.stop().then(() => handleOnPress())
    },
  })

  const { sendReading } = this.props
  NfcManager.registerTagEvent(
    tag => {
      const reading = NdefParser.parseText(tag.ndefMessage[0])
      sendReading(reading)
    },
    'Hold your device over the tag',
    true
  )
}
  • Need an API to refresh NFCNDEFReaderSession
  • I've tried re-rendering this component, even rendering another one then coming back, and it is stuck
  • I randomly got a warning of Sending `NfcMangerSessionClosed` with no listeners registered. -- it may be related to that?

Android + iOS NFC permissions

Hi we are using this package and are very impressed.

Just was curious, is the package asking for permissions to use NFC on the device (Android / iOS) or should / can we add that manually?

e.g. on Android (AndroidManifest.xml):

<uses-permission android:name="android.permission.NFC" />

Unable to parse Plain text from Nfc Tag

How to parse plain text (Not URI) from a tag?
We can see the tag data in payload, But we are unable to parse the text data .
Is there any method to parse "plain-text"?

NfcManager is undefined when using wix/react-native-navigation (Android)

Hi @whitedogg13,

Thanks for all your work on this, I'm excited to start using it. I've tried both your sample app and building some code into my own app and I'm seeing an issue where NfcManager is undefined:

import NfcManager, {NdefParser} from 'react-native-nfc-manager';

export default class Login extends React.Component {
  componentDidMount() {
    NfcManager.isSupported().then((isSupported) => Alert.alert(isSupported));
  }
}

When I run this app, I get this error:

TypeError: Cannot read property 'isSupported' of undefined

Any idea what I might be missing?

NFC Scan Sounds

Hi, I'm trying to disable the native scan sound so that I can use my own instead. Is there any way to use the enableReaderMode API instead of enableForegroundDispatch so that I can use the FLAG_READER_NO_PLATFORM_SOUNDS flag?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.