Git Product home page Git Product logo

flutter-nfc-manager's Introduction

nfc_manager

Flutter plugin for accessing the NFC features on Android and iOS.

Note: This plugin depends on NFCTagReaderSession (requires iOS 13.0 or later) and NfcAdapter#enableReaderMode (requires Android API level 19 or later).

Setup

Android Setup

iOS Setup

Usage

Handling Session

// Check availability
bool isAvailable = await NfcManager.instance.isAvailable();

// Start Session
NfcManager.instance.startSession(
  onDiscovered: (NfcTag tag) async {
    // Do something with an NfcTag instance.
  },
);

// Stop Session
NfcManager.instance.stopSession();

Handling Platform Tag

The following platform-tag-classes are available:

  • Ndef
  • FeliCa (iOS only)
  • Iso7816 (iOS only)
  • Iso15693 (iOS only)
  • MiFare (iOS only)
  • NfcA (Android only)
  • NfcB (Android only)
  • NfcF (Android only)
  • NfcV (Android only)
  • IsoDep (Android only)
  • MifareClassic (Android only)
  • MifareUtralight (Android only)
  • NdefFormatable (Android only)

Obtain an instance by calling the factory constructor from on the class. For example:

Ndef? ndef = Ndef.from(tag);

if (ndef == null) {
  print('Tag is not compatible with NDEF');
  return;
}

// Do something with an Ndef instance

Please see the API Doc for more details.

Real-World-App

See this repo which is a Real-World-App demonstrates how to use this plugin.

flutter-nfc-manager's People

Contributors

fabienrousseau avatar fossati-ibt avatar fred441a avatar fritzmatthaeus avatar okadan avatar thomasaunvik 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

flutter-nfc-manager's Issues

i got error java.lang.RuntimeException: Tag incorrectly enumerated as MIFARE Classic, SAK = 32

D/AndroidRuntime(22979): Shutting down VM
E/AndroidRuntime(22979): FATAL EXCEPTION: main
E/AndroidRuntime(22979): Process: com.jm.travoy, PID: 22979
E/AndroidRuntime(22979): java.lang.RuntimeException: Tag incorrectly enumerated as MIFARE Classic, SAK = 32
E/AndroidRuntime(22979): at android.nfc.tech.MifareClassic.(MifareClassic.java:200)
E/AndroidRuntime(22979): at android.nfc.tech.MifareClassic.get(MifareClassic.java:138)
E/AndroidRuntime(22979): at io.flutter.plugins.nfcmanager.TranslatorKt.getTagMap(Translator.kt:88)
E/AndroidRuntime(22979): at io.flutter.plugins.nfcmanager.NfcManagerPlugin$handleNfcStartSession$1$1.run(NfcManagerPlugin.kt:110)
E/AndroidRuntime(22979): at android.os.Handler.handleCallback(Handler.java:883)
E/AndroidRuntime(22979): at android.os.Handler.dispatchMessage(Handler.java:100)
E/AndroidRuntime(22979): at android.os.Looper.loop(Looper.java:214)
E/AndroidRuntime(22979): at android.app.ActivityThread.main(ActivityThread.java:7540)
E/AndroidRuntime(22979): at java.lang.reflect.Method.invoke(Native Method)
E/AndroidRuntime(22979): at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
E/AndroidRuntime(22979): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:980)
I/Process (22979): Sending signal. PID: 22979 SIG: 9
Lost connection to device.

Android 10

Question: ISO-14443A (NTAG213) support for both android & ios

Hi

I'm going to start a flutter cross-platform project and use your package as NFC manager.
As for the NFC tag, I'm going to use the NTAG213 chipset (ISO-14443-A), just want to read/write an URL on it, and I need to know that your package can support this tag and chipset on both android and ios (Right now NFC tag is not available for me to test your package).

It would be so nice to get your response soon.
With regards

Exception writing to read only tag. Needs a better message in exception.

I'm on Android, I try and write to a readonly tag, but I get back a blank PlatformException rather than a useful message like 'tag is readonly'.

Error comes from final T typedResult = codec.decodeEnvelope(result);
Exception has occurred.
PlatformException (PlatformException(io_exception, null, null))

iOS ISO7816Tag.sendCommand returns empty string

After tag session started and tag is found, commands are sent down to card, but there are no response codes to see if it actually succeded.
Code snippet:

    NfcManager.instance.startTagSession(onDiscovered: (NfcTag tag) async {
      dynamic c;
      Platform.isAndroid ? c = IsoDep.fromTag(tag) : c = ISO7816.fromTag(tag);
      Uint8List aid = Uint8List.fromList(
          [0xd3, 0x92, 0xf0, 0x00, 0x26, 0x01, 0x00, 0x00, 0x00, 0x01]);
      String recvData;
      try {
        Uint8List recvDataByte;
        Platform.isAndroid
            ? recvDataByte = await c.transceive(commandLine)
            : recvDataByte = await c.sendCommand(
                instructionClass: 0x00, //CLA
                instructionCode: 0xA4, //INS
                p1Parameter: 0x04, //P1
                p2Parameter: 0x0C, //P2
                data: aid,
                expectedResponseLength: 0xFF); //Le

        while (recvDataByte == null) bool wait = true;
        recvData = bytesToString(recvDataByte);

        print("tested comand result: " + recvData);
      } catch (e) {
        print(e.toString());
      }
    });

Tested card in example is a MyNumber card.

Can't get it to work on iOS

For some reason if I try to use this plugin with an iPhone it won't work. Nothing happens if I use the example code and tap a empty NFC Tag on the back of the phone. I will only get this error: [CoreNFC] 00000002 81c8b4e0 -[NFCTagReaderSession beginSessionWithConfig:]:378 error:Error Domain=NFCError Code=203 "System resource unavailable" UserInfo={NSLocalizedDescription=System resource unavailable}, errorCode: 0xcb

Read data from the sector?

Hi,

I am able to see the information like "id", "nfca", "maxTransceiveLength", "mifareclassic". Under "mifareclassic" there is block count, maxtransceivelength, sectorcount, size and timeout information.

Are we able to read the data from different sector? I wish to retrieve the information in the card.

Thanks!

Exception: decodeObjectForKey: class "NFFieldNotification" not loaded or does not exist

IOS version: 13.2.3

Error occurs after initiation of Read/ Write events on both devices.

[xpc.exceptions] NSXPCConnection: connection to service on pid 85 named com.apple.nfcd.service.corenfc: Exception caught during decoding of received selector didDetectExternalReaderWithNotification:, dropping incoming message.

Exception: Exception while decoding argument 0 (# 2 of invocation):
Exception: decodeObjectForKey: class "NFFieldNotificationECP1_0" not loaded or does not exist

Note: Events are getting triggered, Ready To scan Popup is disappearing.

[ios] Unhandled Exception: PlatformException(unavailable, Only available in iOS 13.0 or newer, null, null)

given

  • flutter create nfc_ios
  • add to ios\runner the file Runner.entitlements with
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
	<key>com.apple.developer.nfc.readersession.formats</key>
	<array>
		<string>TAG</string>
	</array>
</dict>
</plist>
  • add to plist
	<!-- added for nfc START -->
	<key>NFCReaderUsageDescription</key>
	<string>Read NFC Tags</string>
	<!-- added for nfc STOP -->
	
  • add code
import 'package:flutter/material.dart';
import 'package:nfc_manager/nfc_manager.dart';

void _justPrint() async {
  final instance = NfcManager.instance;
  if (await instance.isAvailable()) {
    instance.startSession(onDiscovered: (tag) async {
      for (final entry in tag.data.entries) {
        print('key ${entry.key}');
        print('value ${entry.value}');
      }
      print(tag.handle);
    });
  }
}

void main() => runApp(const MaterialApp(home: JustListen()));

class JustListen extends StatefulWidget {
  const JustListen({Key? key}) : super(key: key);

  @override
  _JustListenState createState() => _JustListenState();
}

class _JustListenState extends State<JustListen> {
  @override
  void initState() {
    _justPrint();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return const Material(child: Center(child: CircularProgressIndicator()));
  }
}
logs
[ +205 ms] [ 52%] CreatingStagingDirectory
[        ] [ 57%] ExtractingPackage
[        ] [ 60%] InspectingPackage
[  +57 ms] [ 60%] TakingInstallLock
[ +249 ms] [ 65%] PreflightingApplication
[        ] [ 67%] PatchingApplication
[ +164 ms] [ 67%] InstallingEmbeddedProfile
[  +23 ms] [ 70%] VerifyingApplication
[+1471 ms] [ 75%] CreatingContainer
[  +12 ms] [ 80%] InstallingApplication
[  +18 ms] [ 85%] PostflightingApplication
[   +6 ms] [ 90%] SandboxingApplication
[  +33 ms] [ 95%] GeneratingApplicationMap
[ +948 ms] [100%] Installed package build/ios/iphoneos/Runner.app
[ +165 ms] ------ Debug phase ------
[        ] Starting debug of 42f545c80499280e43186687e3c51ad278ab2985 (N61AP, iPhone 6 (GSM), iphoneos, arm64) a.k.a. 'xxxx iPhone' connected through USB...
[ +535 ms] [  0%] Looking up developer disk image
[  +30 ms] [ 95%] Developer disk image mounted successfully
[ +726 ms] [100%] Connecting to remote debug server
[        ] -------------------------
[  +34 ms] (lldb) command source -s 0 '/tmp/E059A27B-9BA1-41D5-8C6B-6DF7CAEA822A/fruitstrap-lldb-prep-cmds-42f545c80499280e43186687e3c51ad278ab2985'
[        ] Executing commands in '/tmp/E059A27B-9BA1-41D5-8C6B-6DF7CAEA822A/fruitstrap-lldb-prep-cmds-42f545c80499280e43186687e3c51ad278ab2985'.
[        ] (lldb)     platform select remote-ios --sysroot '/Users/xxx/Library/Developer/Xcode/iOS DeviceSupport/12.4.4 (16G140)/Symbols'
[        ]   Platform: remote-ios
[        ]  Connected: no
[        ]   SDK Path: "/Users/xxx/Library/Developer/Xcode/iOS DeviceSupport/12.4.4 (16G140)/Symbols"
[        ] (lldb)     target create "/Users/xxx/development/nfc_ios/build/ios/iphoneos/Runner.app"
[+3686 ms] Current executable set to '/Users/xxx/development/nfc_ios/build/ios/iphoneos/Runner.app' (arm64).
[        ] (lldb)     script fruitstrap_device_app="/private/var/containers/Bundle/Application/BC09B299-4916-4348-884A-388256129132/Runner.app"
[ +347 ms] (lldb)     script fruitstrap_connect_url="connect://127.0.0.1:58751"
[        ] (lldb)     script fruitstrap_output_path=""
[        ] (lldb)     script fruitstrap_error_path=""
[        ] (lldb)     target modules search-paths add /usr "/Users/xxx/Library/Developer/Xcode/iOS DeviceSupport/12.4.4 (16G140)/Symbols/usr" /System "/Users/xxx/Library/Developer/Xcode/iOS DeviceSupport/12.4.4
(16G140)/Symbols/System" "/private/var/containers/Bundle/Application/BC09B299-4916-4348-884A-388256129132" "/Users/xxx/development/nfc_ios/build/ios/iphoneos" "/var/containers/Bundle/Application/BC09B299-4916-4348-884A-388256129132"
"/Users/xxx/development/nfc_ios/build/ios/iphoneos" /Developer "/Users/xxx/Library/Developer/Xcode/iOS DeviceSupport/12.4.4 (16G140)/Symbols/Developer"
[  +12 ms] (lldb)     command script import "/tmp/E059A27B-9BA1-41D5-8C6B-6DF7CAEA822A/fruitstrap_42f545c80499280e43186687e3c51ad278ab2985.py"
[   +3 ms] (lldb)     command script add -f fruitstrap_42f545c80499280e43186687e3c51ad278ab2985.connect_command connect
[        ] (lldb)     command script add -s asynchronous -f fruitstrap_42f545c80499280e43186687e3c51ad278ab2985.run_command run
[        ] (lldb)     command script add -s asynchronous -f fruitstrap_42f545c80499280e43186687e3c51ad278ab2985.autoexit_command autoexit
[        ] (lldb)     command script add -s asynchronous -f fruitstrap_42f545c80499280e43186687e3c51ad278ab2985.safequit_command safequit
[        ] (lldb)     connect
[  +37 ms] (lldb)     run
[ +271 ms] success
[        ] (lldb)     safequit
[ +120 ms] Process 403 detached
[  +33 ms] Application launched on the device. Waiting for observatory port.
[+1259 ms] Observatory URL on device: http://127.0.0.1:54922/
[   +7 ms] Attempting to forward device port 54922 to host port 58761
[        ] executing: /Users/xxx/fvm/versions/stable/bin/cache/artifacts/usbmuxd/iproxy 58761:54922 --udid 42f545c80499280e43186687e3c51ad278ab2985
[+1014 ms] Forwarded port ForwardedPort HOST:58761 to DEVICE:54922
[        ] Forwarded host port 58761 to device port 54922 for Observatory
[   +3 ms] Installing and launching... (completed in 11.7s)
[   +2 ms] Caching compiled dill
[  +76 ms] Connecting to service protocol: http://127.0.0.1:58761/
[ +376 ms] Launching a Dart Developer Service (DDS) instance at http://127.0.0.1:0, connecting to VM service at http://127.0.0.1:58761/.
[ +111 ms] DDS is listening at http://127.0.0.1:58764/NxGQy33a8q0=/.
[  +59 ms] Successfully connected to service protocol: http://127.0.0.1:58761/
[  +27 ms] DevFS: Creating new filesystem on the device (null)
[  +49 ms] DevFS: Created new filesystem on the device (file:///private/var/mobile/Containers/Data/Application/C8206186-F545-463E-906F-5D6E2A2052B0/tmp/nfc_ios3cHwNg/nfc_ios/)
[   +2 ms] Updating assets
[  +92 ms] Syncing files to device xxx iPhone...
[   +1 ms] <- reset
[        ] Compiling dart to kernel with 0 updated files
[   +2 ms] <- recompile package:nfc_ios/main.dart 53d5d210-693c-4a5d-b854-49157bbed721
[        ] <- 53d5d210-693c-4a5d-b854-49157bbed721
[  +65 ms] Updating files.
[        ] DevFS: Sync finished
[   +2 ms] Syncing files to device xxx iPhone... (completed in 70ms)
[        ] Synced 0.0MB.
[   +1 ms] <- accept
[  +12 ms] Connected to _flutterView/0x14e037e20.
[   +3 ms] Flutter run key commands.
[   +1 ms] r Hot reload. 🔥🔥🔥
[   +1 ms] R Hot restart.
[        ] h Repeat this help message.
[        ] d Detach (terminate "flutter run" but leave application running).
[        ] c Clear the screen
[        ] q Quit (terminate the application on the device).
[        ] 💪 Running with sound null safety 💪
[        ] An Observatory debugger and profiler on xxx iPhone is available at: http://127.0.0.1:58764/NxGQy33a8q0=/
[ +540 ms] The Flutter DevTools debugger and profiler on xxx iPhone is available at: http://127.0.0.1:9101?uri=http%3A%2F%2F127.0.0.1%3A58764%2FNxGQy33a8q0%3D%2F
[ +264 ms] [VERBOSE-2:ui_dart_state.cc(199)] Unhandled Exception: PlatformException(unavailable, Only available in iOS 13.0 or newer, null, null)
[        ] #0      StandardMethodCodec.decodeEnvelope (package:flutter/src/services/message_codecs.dart:597:7)
[        ] #1      MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:158:18)
[        ] <asynchronous suspension>
[        ] #2      _justPrint (package:nfc_ios/main.dart:6:7)
[        ] <asynchronous suspension>
[+18713 ms] DevFS: Deleting filesystem on the device (file:///private/var/mobile/Containers/Data/Application/C8206186-F545-463E-906F-5D6E2A2052B0/tmp/nfc_ios3cHwNg/nfc_ios/)
[  +30 ms] DevFS: Deleted filesystem on the device (file:///private/var/mobile/Containers/Data/Application/C8206186-F545-463E-906F-5D6E2A2052B0/tmp/nfc_ios3cHwNg/nfc_ios/)
[ +119 ms] Service protocol connection closed.
[        ] Application finished.
[   +5 ms] "flutter run" took 47,754ms.
[  +85 ms] ensureAnalyticsSent: 82ms
[   +1 ms] Running shutdown hooks
[        ] Shutdown hooks complete
[        ] exiting with code 0
doctor
[✓] Flutter (Channel stable, 2.2.2, on macOS 11.4 20F71 darwin-x64, locale en-EE)
    • Flutter version 2.2.2 at /Users/xxx/fvm/versions/stable
    • Framework revision d79295af24 (5 days ago), 2021-06-11 08:56:01 -0700
    • Engine revision 91c9fc8fe0
    • Dart version 2.13.3

[✓] Android toolchain - develop for Android devices (Android SDK version 30.0.3)
    • Android SDK at /Users/xxx/Library/Android/sdk
    • Platform android-30, build-tools 30.0.3
    • Java binary at: /Applications/Android Studio.app/Contents/jre/jdk/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 11.0.8+10-b944.6916264)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Xcode 12.5, Build version 12E262
    • CocoaPods version 1.10.1

[✓] Chrome - develop for the web
    • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

[✓] Android Studio (version 4.2)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/6351-dart
    • Java version OpenJDK Runtime Environment (build 11.0.8+10-b944.6916264)

[✓] VS Code (version 1.57.0)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 3.23.0

[✓] Connected device (3 available)
    • xxx’s iPhone (mobile) • xxx • ios            • iOS 12.4.4
    • macOS (desktop)             • macos                                    • darwin-x64     • macOS 11.4 20F71 darwin-x64
    • Chrome (web)                • chrome                                   • web-javascript • Google Chrome 91.0.4472.106
pubspec
name: nfc_ios
description: A new Flutter project.
version: 1.0.0+1

environment:
  sdk: ">=2.12.0 <3.0.0"

dependencies:
  flutter:
    sdk: flutter
  nfc_manager: ^3.1.0

dev_dependencies:
  flutter_test:
    sdk: flutter

flutter:
  uses-material-design: true

note

same code works perfectly on android

Couldn't able to write in android Ndef.from(tag) returning null on android

NfcManager.instance.startSession(pollingOptions: {NfcPollingOption.iso14443,NfcPollingOption.iso15693}, onDiscovered: (NfcTag tag) async {
var ndef = Ndef.from(tag);
print(ndef); //print null
if (ndef == null || !ndef.isWritable) {
result.value = 'Tag is not ndef writable';
NfcManager.instance.stopSession(errorMessage: result.value);
return;
}else{
print("writable");
}

on Null couldn't able to write but if there is already have a data it is working properly

GetFeliCaReadWithoutEncryptionResponse occurred exception

The following exception has occurred.

type List<dynamic> is not a subtype of type List<Uint8List>
return FeliCaReadWithoutEncryptionResponse(
    statusFlag1: arg['statusFlag1'],
    statusFlag2: arg['statusFlag2'],
    blockData: arg['blockData'],
);

The cause is this source.

blockData: arg['blockData']

Fix it like this.

blockData: arg['blockData'].cast<Uint8List>() as List<Uint8List>

Read credit card information

Hello everyone,

How can I read the information on a VISA NFC credit card?

I've done a lot of research and can't find anything related.

Is there an example for me to base myself on?

NFC reader is always listening on Android

Hi there, thank you for this plugin it's working great!

I have an issue on Android where the scanner is always listening. I only want it to listen for NFC tag reads when tapping a button to activate the scanner. Is there any way to prevent the scanner from always listening?

Increase the session timeout (Scanning time) in iOS

I'm using this plugin in my app. I have a scenario where I need to send multiple commands with binary data to my nfc tag (ISO 15693). Sending this data takes almost 40-45 seconds. Ideally, I want the 'Ready to scan' popup till all the data is sent to the charger. But it closes (with check tick mark) after around 30 secs and then I get an error '[CoreNFC] 00000002 81002300 -[NFCTagReaderSession transceive:tagUpdate:error:]:710 Error Domain=NFCError Code=100 "Tag connection lost" UserInfo={NSLocalizedDescription=Tag connection lost}'.

Is there a way to increase the nfc scanning time (or exrend the nfc reader session)?

Issue with non-NFC devices

I made an android app that has NFC scanning and it works perfectly. For non-NFC devices, I made another option for scanning. The problem is that I can't even build an app on a non-NFC device. There is an exception:

Caused by: java.lang.IllegalStateException: NfcAdapter.getDefaultAda…nding.applicationContext) must not be null
E/AndroidRuntime(30997): 	at io.flutter.plugins.nfcmanager.NfcManagerPlugin.onAttachedToEngine(NfcManagerPlugin.kt:65)
E/AndroidRuntime(30997): 	at io.flutter.embedding.engine.FlutterEnginePluginReg

What to do to have buildable app for any android device but to use NFC with nfc-manager on device with NFC?
Thanks

Feature Request: Password Protected Tags

Hello all,
I think a rather useful feature would be to be able to password protect new/existing tags or create read only tags. This is supported by some NDEF formatted cards and would allow these tags to be placed in public places, without making them vulnerable to sabotage or even accidental writing.
Password protected tags would require the password to be removed to make them writable (they'd always be readable). Read only tags would never be able to be written again.
Thanks, and I hope this idea does get implemented because it is a main idea of my app.

ios14 ndef.write(message) error

void _ndefWrite(NfcTag tag, String eid) {
Ndef ndef = Ndef.from(tag);
if (ndef == null || !ndef.isWritable) {
result.value = 'Tag is not ndef writable';
NfcManager.instance.stopSession(errorMessage: result.value);
return;
}

NdefMessage message = NdefMessage([
  NdefRecord.createUri(Uri.parse(AppConfig.web_url_User_card_home + eid)),
]);

try {
  ndef.write(message);

}
}

how to set ios14 write error?

How can I read credit card detail with this plugin?

Hi, I can read 1 arcade game card with this plugin but fail to read credit card detail through the app with the phone nfc.
Do you know how can I read nfc detail with this plugin?
E.g. With phone nfc, i wanna get credit card details of the credit card that's tapped, like cc number, expiry date, name, etc.

NFC transceive fails at second transmission on Android.

I try to use the NfcV class to transmit some commands to a corresponding tag. I registered the following function as callback for the onDiscovered events. The result is a correct answer on the first try and an exception on the second try. Did I do it wrong?

Future callbackFunction(NfcTag tag) async {
  final nfcVtag = NfcV.fromTag(tag);
  final cmd = [0x02, 0x20, 0x00].toList();
  try {
    final answer = await nfcVtag.transceive(Uint8List.fromList(cmd));
    debugPrint('First answer ' + answer.toString());
  } catch (e) {
    debugPrint('Exception on first try: ' + e.toString());
  }
  try {
    final answer = await nfcVtag.transceive(Uint8List.fromList(cmd));
    debugPrint('Second answer ' + answer.toString());
  } catch (e) {
    debugPrint('Exception on second try: ' + e.toString());
  }
}

Output:

I/flutter (17066): First answer [0, 167, 19, 240, 84, 5, 0, 3, 101]
I/flutter (17066): Exception on second try: PlatformException(not_found, Tag is not found., null)

集成插件

[!] Unable to determine Swift version for the following pods:

  • nfc_manager does not specify a Swift version and none of the targets (Runner) integrating it have the SWIFT_VERSION attribute set. Please contact the author or set the SWIFT_VERSION attribute in at least one of the targets that integrate this pod.

QUESTION: Reading previous write Tag Data

Hi, i like to learn about nfc, i use write tag with your sample and get this response:
Success to "Ndef Write"

but when i read the tag i get this:

{id: [249, 109, 254, 163], nfca: {atqa: [4, 0], maxTransceiveLength: 253, sak: 8, timeout: 618}, mifareclassic: {blockCount: 64, maxTransceiveLength: 253, sectorCount: 16, size: 1024, timeout: 618, type: 0}, ndef: {cachedMessage: {records: [{typeNameFormat: 1, type: [84], identifier: [], payload: [2, 101, 110, 72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33]}, {typeNameFormat: 1, type: [85], identifier: [], payload: [4, 102, 108, 117, 116, 116, 101, 114, 46, 100, 101, 118]}, {typeNameFormat: 2, type: [116, 101, 120, 116, 47, 112, 108, 97, 105, 110], identifier: [], payload: [72, 101, 108, 108, 111]}, {typeNameFormat: 4, type: [99, 111, 109, 46, 101, 120, 97, 109, 112, 108, 101, 58, 109, 121, 116, 121, 112, 101], identifier: [], payload: [109, 121, 100, 97, 116, 97]}]}, canMakeReadOnly: false, isWritable: true, maxSize: 716, type: com.nxp.ndef.mifareclassic}}

how i do to process the payload to see the info as was wrote?

thanks for your help!

transceive() blocking UI thread [android]

Calls to "transceive", "connect" and "close" methods currently blocks the UI and therefore should be called inside a background thread.

To reproduce:

  1. Place CircularProgressIndicator(value: null) in the widget tree
  2. Inside your "onDiscovered", call tag.transceive(data)
  3. The progress indicator stutters for a brief amount of time

Relevant: https://developer.android.com/reference/android/nfc/tech/IsoDep#transceive(byte[])

This is an I/O operation and will block until complete. It must not be called from the main application thread.

Error:nfc.platformexception(io_exception,null,null,null)

Hi, I have this problem with this packages in android. On the various devices it sometimes works but other times it fails. the message that comes out to me is this: nfc.platformexception(io_exception,null,null,null).

Thank you.

NfcManager plugin causes app to crash on launch

Not sure why this is happening?

Installing build/app/outputs/flutter-apk/app.apk... E/AndroidRuntime(22220): FATAL EXCEPTION: main E/AndroidRuntime(22220): Process:com.app.name.developing, PID: 22220 E/AndroidRuntime(22220): java.lang.IllegalStateException: NfcAdapter.getDefaultAda…nding.applicationContext) must not be null E/AndroidRuntime(22220): at io.flutter.plugins.nfcmanager.NfcManagerPlugin.onAttachedToEngine(NfcManagerPlugin.kt:65) E/AndroidRuntime(22220): at io.flutter.embedding.engine.FlutterEnginePluginRegistry.add(FlutterEnginePluginRegistry.java:133) E/AndroidRuntime(22220): at io.flutter.plugins.GeneratedPluginRegistrant.registerWith(GeneratedPluginRegistrant.java:51) E/AndroidRuntime(22220): at com.app.name_flutter.MainActivity.configureFlutterEngine(MainActivity.kt:41) E/AndroidRuntime(22220): at io.flutter.embedding.android.FlutterFragment.configureFlutterEngine(FlutterFragment.java:949) E/AndroidRuntime(22220): at io.flutter.embedding.android.FlutterActivityAndFragmentDelegate.onAttach(FlutterActivityAndFragmentDelegate.java:180) E/AndroidRuntime(22220): at io.flutter.embedding.android.FlutterFragment.onAttach(FlutterFragment.java:583) E/AndroidRuntime(22220): at androidx.fragment.app.Fragment.performAttach(Fragment.java:2574) E/AndroidRuntime(22220): at androidx.fragment.app.FragmentManagerImpl.moveToState(FragmentManagerImpl.java:828) E/AndroidRuntime(22220): at androidx.fragment.app.FragmentTransition.addToFirstInLastOut(FragmentTransition.java:1197) E/AndroidRuntime(22220): at androidx.fragment.app.FragmentTransition.calculateFragments(FragmentTransition.java:1080) E/AndroidRuntime(22220): at androidx.fragment.app.FragmentTransition.startTransitions(FragmentTransition.java:119) E/AndroidRuntime(22220): at androidx.fragment.app.FragmentManagerImpl.executeOpsTogether(FragmentManagerImpl.java:1866) E/AndroidRuntime(22220): at androidx.fragment.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManagerImpl.java:1824) E/AndroidRuntime(22220): at androidx.fragment.app.FragmentManagerImpl.execPendingActions(FragmentManagerImpl.java:1727) E/AndroidRuntime(22220): at androidx.fragment.app.FragmentManagerImpl.dispatchStateChange(FragmentManagerImpl.java:2663) E/AndroidRuntime(22220): at androidx.fragment.app.FragmentManagerImpl.dispatchActivityCreated(FragmentManagerImpl.java:2613) E/AndroidRuntime(22220): at androidx.fragment.app.FragmentController.dispatchActivityCreated(FragmentController.java:246) E/AndroidRuntime(22220): at androidx.fragment.app.FragmentActivity.onStart(FragmentActivity.java:542) E/AndroidRuntime(22220): at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1419) E/AndroidRuntime(22220): at android.app.Activity.performStart(Activity.java:7479) E/AndroidRuntime(22220): at android.app.ActivityThread.handleStartActivity(ActivityThread.java:3454) E/AndroidRuntime(22220): at android.app.servertransaction.TransactionExecutor.performLifecycleSequence(TransactionExecutor.java:180) E/AndroidRuntime(22220): at android.app.servertransaction.TransactionExecutor.cycleToPath(TransactionExecutor.java:165) E/AndroidRuntime(22220): at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:142) E/AndroidRuntime(22220): at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:70) E/AndroidRuntime(22220): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2199) E/AndroidRuntime(22220): at android.os.Handler.dispatchMessage(Handler.java:112) E/AndroidRuntime(22220): at android.os.Looper.loop(Looper.java:216) E/AndroidRuntime(22220): at android.app.ActivityThread.main(ActivityThread.java:7625) E/AndroidRuntime(22220): at java.lang.reflect.Method.invoke(Native Method) E/AndroidRuntime(22220): at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:524) E/AndroidRuntime(22220): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:987)

isoDep transceive exception

I try to get Visa Cardholder name, so I must call transceive a couple of times, transmitting control codes, and in startTagSession I do:

var n = IsoDep.fromTag(tag);
Uint8List res1 = await n.transceive(SELECT);
print('res1: ' + res1.toString());
Uint8List res2 = await n.transceive(GETGPO);
print('res1: ' + res2.toString());

first transceive completes ok, but on second transceive I get:

Unhandled Exception: PlatformException(not_found, Tag is not found., null)

What am I doing wrong?

Issue with iOS 14.4.1 on iPhone 7

I tried out your demo code and also checked out your demo application on my iPhone 7 iOS 14.4.1 and it is not working.

2021-03-19 11:28:29.884901+0100 Runner[403:8791] [CoreNFC] 00000002 83700c20 -[NFCHardwareManager queueReaderSession:sessionConfig:completionHandler:]:96 error=Error Domain=NFCError Code=203 "System resource unavailable" UserInfo={NSLocalizedDescription=System resource unavailable} 2021-03-19 11:28:29.885297+0100 Runner[403:8791] [CoreNFC] 00000002 80558870 -[NFCTagReaderSession beginSessionWithConfig:]:365 error:Error Domain=NFCError Code=203 "System resource unavailable" UserInfo={NSLocalizedDescription=System resource unavailable}, errorCode: 0xcb

This is the exception with your example code.

write lock

can i do unlock NFC card after i locked it and what password is given to card when it lock.

iOS ISO15693 read Multiple Blocks

I always get "Invalid Parameters" & "custom Command code must be between 0xA0 to 0xDF"

What I do:
Set<ISO15693RequestFlag> requestFlags = new Set(); requestFlags.add(ISO15693RequestFlag.highDataRate); requestFlags.add(ISO15693RequestFlag.address); Uint8List command = new Uint8List(10); command[0] = (182); command[1] = (51); command[2] = (59); command[3] = (167); command[4] = (0); command[5] = (38); command[6] = (2); command[7] = (224); command[8] = (165); command[9] = (4); Uint8List response = await iso15693.customCommand(requestFlags: requestFlags, commandCode: 23, parameters: command); debugPrint('Response: ' + response.toString());

equals to the command: 22 23 B6 33 3B A7 00 26 02 E0 A5 04
right?

But I can't get any response.

NFC session on Android fails to resume

I tried to release and reacquire an NFC session with the following code. This is so that I would get discovery callbacks after my app was intermittently paused (e.g. user switched to another app). The following uses the WidgetsBindingObserver to detect lifecycle changes.

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    if (state == AppLifecycleState.resumed) {
      NfcManager.instance.startTagSession(
          onDiscovered: (NfcTag tag) async {
            handleNFC(tag);
          });
    } else {
      NfcManager.instance.stopSession();
    }
  }

However after switching to another app and back my app does not get any more discovery callbacks. So discovery works from the start of the app until the first pause event.

Is it possible to listen on NFC availability?

Hi, thanks for your work!

I would ask you if it could be possible to listen on NFC status changes (ON - OFF). I didn't find any reference to this in the code but I could be wrong.. Is it something that you already implemented? If not, it could be possible to do so?

I would like to show different screens based on the current NFC status and I don't think it's a good idea calling every 'n' seconds isAvailable() method.

Thanks in advance!

Max

the resulat is different with a lector in windows

Hello,
I use this plugin to read the mifare card.
this is the data read by plugin:
{nfca: {identifier: [199, 255, 228, 52], atqa: [4, 0], maxTransceiveLength: 253, sak: 8, timeout: 618}, mifareclassic: {identifier: [199, 255, 228, 52], blockCount: 64, maxTransceiveLength: 253, sectorCount: 16, size: 1024, timeout: 618, type: 0}, ndefformatable: {identifier: [199, 255, 228, 52]}}
an this is the data read by lector in windows:
0887422919

How can I read the same data as the lector in windows?
Thanks.

how to convert function byte string to dart

public static final byte[] f1504a = {48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 65, 66, 67, 68, 69, 70};
public static final byte[] bArr = {96, 50, (byte) 152, 96, (byte) 147, 80, (byte) 147, 18, 36, 17, 1, 32, (byte) 145, 17, 4, 84, 0, (byte) 145, 3, 1, 6, 0, 0, 0, 0, 0, 3, 116, 87, (byte) 175, 116, 7, (byte) 174, (byte) 206, (byte) 244, 15, (byte) 227, (byte) 162, 68, 9, (byte) 244, (byte) 236, 73, 59, 3, 84, 120, (byte) 132, (byte) 182, (byte) 174, (byte) 176, 80, (byte) 195, 0, 17, 1, 32, 3, (byte) 246, 61, 13, (byte) 255, (byte) 255, (byte) 144, 0};

*bArr is my result 2 layer transceive with nfc_manager

public static String b(byte[] bArr, int i) {
    byte[] bArr2 = new byte[(i * 2)];
    int i2 = 0;
    int i3 = 0;
    for (byte b2 : bArr) {
        if (i2 >= i) {
            break;
        }
        i2++;
        int i4 = b2 & 255;
        int i5 = i3 + 1;
        byte[] bArr3 = f1504a;
        bArr2[i3] = bArr3[i4 >>> 4];
        i3 = i5 + 1;
        bArr2[i5] = bArr3[i4 & 15];
    }
    return new String(bArr2);
}

b(bArr, 8);

I tested this with java and the result 6032986093509312 same with my nfc card number

how i make function like this in dart / flutter. thanks for answering

Failed to load CoreNFC on ios crash.

dyld: Library not loaded: /System/Library/Frameworks/CoreNFC.framework/CoreNFC
Referenced from: /var/containers/Bundle/Application/EB1AFB0C-E3D8-4400-ACED-58AB61EA86F9/Runner.app/Runner
Reason: image not found

I noticed nfc_in_flutter has this in their podspec, I tried this, but it didn't help.
s.weak_frameworks = ['CoreNFC']

Possible fix: https://stackoverflow.com/questions/44946057/dyld-library-not-loaded-rpath-corenfc-framework-corenfc-ios11-and-xcode-9-be

or see: semlette/nfc_in_flutter#20

I just updated Xcode, not sure if this was the cause, but it just started happening.

I'm testing on an iPhone 6.

I tried a bunch of stuff online. Nothing worked. But I found this: https://medium.com/5-minute-break-while-coding/create-a-mostly-swift-framework-with-optional-features-7e8a9ac960f9

Will there be any implementation of getting the UID/ID from an NFC Tag?

Hello, I'm trying to make a login app which utilises the UID/ID of an NFC Card/Tag to log the user in. I can obtain the value in Android using nfc_in_flutter (another package) but I cant use that here because it doesn't seem to even register the nfc card being infront of the phone. Only yours (nfc_manager) works and actually detects the card when placed infront of the phone.

The NFC tag I'm using currently is ISO14443, so I set the polling option to that within session start.

And so I ask, will there be any implementation of getting UID/ID from NFC tags? Because currently on session start of the NFC Manager, once we hover the nfc tag over, we get back
{mifare: {identifier: [4, 40, 252, 242, 37, 94, 129], historicalBytes: [], mifareFamily: 2}, ndef: {isWritable: true, maxSize: 137}}
the data received seems to be everything but the ID, which is a bit weird.

Thanks!

Integration plug-in

[!] Unable to determine Swift version for the following pods:

  • nfc_manager does not specify a Swift version and none of the targets (Runner) integrating it have the SWIFT_VERSION attribute set. Please contact the author or set the SWIFT_VERSION attribute in at least one of the targets that integrate this pod.

IOS Release mode not working

Well the title is self-explanatory, I can get to work the nfc perfectly in debug build but I cant get it to work on a release one.

Any hint would be appreciated.

MetaData UUID

Can I access uuid of nfc? I can't find any information in your library code API and docs.

iOS iso7816 sendCommand Response Error

I'm working on reading an iso1443-4 card on iOS. It works well on Swift code but failed in the flutter project.

Code with flutter-nfc-manager

iso7816Tag.sendCommandRaw(Uint8List.fromList([0x00, 0xA4, 0x04, 0x00, 0x08, 0x50, 0x41, 0x59, 0x2E, 0x54, 0x49, 0x43, 0x4C, 0x00])).then((value) =>
{
   print("select App response ${value}")
});

flutter-nfc-manager Response

flutter: select App response []
[CoreNFC] 00000002 8001cb40 -[NFCTagReaderSession setAlertMessage:]:90  (null)

The command is correct, it works well in Xcode with swift.

Code with Swift

let selectApp : NFCISO7816APDU = NFCISO7816APDU(data: Data.init([0x00, 0xA4, 0x04, 0x00, 0x08, 0x50, 0x41, 0x59, 0x2E, 0x54, 0x49, 0x43, 0x4C, 0x00]))!
            
session.connect(to: tag0!) { (e: Error?) in tag?.sendCommand(apdu: selectApp, completionHandler: { (data: Data, sw1: UInt8, sw2: UInt8, error: Error?) in
  print("selectApp APDU Result \(data.hexDescription)")
})
}

Swift Response

selectApp APDU Result 6f3484085041592e5449434ca5289f0801029f0c21ffffffffffffffff000000000000000000000000000000002019082400000186a0

Please help to confirm the issues. 🙏

Can You Add Password Feature

Hello,

Can you add the password feature in this library? 'Cause I want to rewrite NFC tag with the password, the lock feature makes NFC unusable.

thanks

App to send data from one phone to NFC device

Hi,
I'd need to create an app to use NFC to receive and send data to a device.
I want to detect the device, read its ID , do a process in the app, and send a OK message to that device. Can I do it with this package with a flutter app?
please let me know
thanks so much for your help

iOS popover cancel button event

Hi @okadan

first of all great work!

I am using your package in a project where I read a NfcTag and later use the tag id to call some server logic. Overall I am using the BLoC-pattern and I am wondering if there is an option to catch the "on cancel"-event when you tap the button on the Nfc-Popover in iOS. I differentiate between two states IsReadyToReadNfc and ReadingNfc. Depending on the state I have a button and want to display either "Start Scanning" or "Scanning..."

nfc manager does not check NFC permission.

I found 2 issues about the nfc permission.

  1. "request permission" is shown at second time, not at first time.
    When startSession() is called 2 times, "request permission" is shown.

  2. status of permission is not checked.
    Even though a user denies the nfc permission, nfc_manager keeps to access to nfc.

using version nfc_manager: ^2.0.0+2

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.