Skip to content
Titanium SDK

ti.nfc

Officialtidev/ti.nfc

Read Android NFC sensors with the Titanium SDK.

4.1.1iOSApr 18, 2024v4.1.1-iphone

Install

A module is a zip you unpack in your project. There is no installer command yet - a ti module install is planned but does not exist today, so the steps below are the ones that work.

  1. 1. Download the release archive

  2. 2. Unpack it at your project root

    cd /path/to/your-project
    unzip ~/Downloads/ti.nfc-iphone-4.1.1.zip

    The archive already contains the full path, so it lands in place:

    • modules/iphone/ti.nfc/4.1.1/
  3. 3. Add it to tiapp.xml

    <modules>
      <module platform="iphone" version="4.1.1">ti.nfc</module>
    </modules>

    The platform attribute is the packager’s name for the platform, which is iphone for iOS - the same word the archive uses in its own path.

  4. 4. Require it from your app

    const mod = require('ti.nfc');

Manifest

iOS 4.1.1

Minimum SDK
9.2.0
Module API version
2
Architectures
arm64, x86_64
GUID
50513178-f1da-40e1-8031-75c08db86d6f
Author
Hans Knoechel
License
Apache 2
Copyright
Copyright (c) 2017-present by Appcelerator
Mac Catalyst
supported

API reference

Compiled from tidev/ti.nfc@4.1.1 (7f72b46).

Modules.Nfc

moduleAndroidiPhonesince Android 1.0.0, iPhone 2.0.0

Extends Titanium.Module

A cross-platform Near-Field-Communication (NFC) module for iOS and Android. Download the latest release via Github.

This module provides access to Near Field Communication (NFC) functionality, allowing applications to read and write (Android-only) NFC tags. A "tag" may actually be another device that appears as a tag.

NFC Resources

Requirements

  • Android

    • Android 4.1 (API 16) and later
    • An NFC capable device
  • iOS

    • iOS 11 and later
    • iPhone 7 / iPhone 7 Plus and later

Getting Started

  • View the Using Titanium Modules document for instructions on getting started with using this module in your application.

Configure iOS: Capabilities and Provisioning Profiles

  • Required capabilities:

    <key>com.apple.developer.nfc.readersession.formats</key>
    <array>
        [string](api:Global.String)NDEF</string>
    </array>
  • Provisioning Profile entitled with the NFC Tag Reading capability

Configure Android: Tag Dispatching and Intent Filters

  • The Android tag dispatch system is responsible for dispatching NFC messages to the appropriate application. In the situation where you are not using foreground dispatching, you will need to define intent-filters in the tiapp.xml file to specify which types of NFC messages the application wants to receive. By using intent-filters in the tiapp.xml file, the application will be automatically started if a matching NFC message is dispatched.

    Add code similar to the following to your tiapp.xml file:

    • Replace occurrences of the activity name (Tagviewer) with your activity name.

    • Add the NFC permissions to your Android configuration

    • Replace the NFC specific intent filters with filters appropriate for your application.

      <android xmlns:android="http://schemas.android.com/apk/res/android">
          <manifest>
              <!-- Required NFC permissions -->
              <uses-permission android:name="android.permission.NFC" />
              <uses-feature android:name="android.hardware.nfc" android:required="true" /> 
              
              <!-- NFC Intent filters -->
              <application>
                  <activity android:name=".TagviewerActivity"
                    android:label="TagViewer" android:theme="@style/Theme.Titanium"
                    android:configChanges="keyboardHidden|orientation"
                    android:exported="true">
                      <intent-filter>
                          <action android:name="android.nfc.action.TECH_DISCOVERED"/>
                          <category android:name="android.intent.category.DEFAULT"/>
                      </intent-filter>
      
                      <intent-filter>
                          <action android:name="android.nfc.action.NDEF_DISCOVERED"/>
                          <category android:name="android.intent.category.DEFAULT"/>
                          <data android:mimeType="text/plain" />
                      </intent-filter>
      
                      <intent-filter>
                          <action android:name="android.nfc.action.TAG_DISCOVERED"/>
                          <category android:name="android.intent.category.DEFAULT"/>
                      </intent-filter>
                  </activity>
              </application>
          </manifest>
      </android>

    Note that if you are using foreground dispatching you do not need to define intent filters in the application's tiapp.xml file.

Accessing the Module

  • Use require to access this module from JavaScript:

    var nfc = require('ti.nfc');

    The nfc variable is a reference to the Module object.

Creating an Adapter

  • The NFC adapter gives you access to the features of the NFC device. The NFC adapter proxy is always associated with the activity that was the current activity when it was created. Therefore, the NFC Adapter should be created after the activity has been opened. You can use the window open event to know when the activity has been opened.

    $.index.addEventListener('open', function(e) {
        nfcAdapter = nfc.createNfcAdapter({
            onNdefDiscovered: handleDiscovery,
            onTagDiscovered: handleDiscovery, // Android-only
            onTechDiscovered: handleDiscovery // Android-only
        });
    
        if (!nfcAdapter.isEnabled()) {
            Ti.API.error('NFC is not enabled on this device!');
            return;
        }
    });

Handling Intents (Android)

  • NFC Intents are dispatched to an activity by the Android tag dispatch system. When your activity receives a new intent, it must forward the intent to the onNewIntent method of the NFC adapter for processing.

    Ti.Android.currentActivity.addEventListener('newintent', function (e) {
        nfcAdapter.onNewIntent(e.intent);
    });

    If your application is started as the result of an NFC intent, that intent will automatically be processed when the NFC module is loaded.

Foreground Dispatch

  • The foreground dispatch system allows an activity to intercept an intent and claim priority over other activities that handle the same intent. When using foreground dispatching, you must process the pause and resume events on the activity and enable or disable foreground dispatching.

    var currentActivity = Ti.Android.currentActivity;
    
    currentActivity.addEventListener('resume', function(e) {
        nfcAdapter.enableForegroundDispatch(dispatchFilter);
    });
    currentActivity.addEventListener('pause', function(e) {
        nfcAdapter.disableForegroundDispatch();
    });

Example applications

  • Android example applications are located in the example/android folder of the module:

    • TagBeam demonstrates how to use Android Beam to send messages to another NFC capable device.
    • TagForeground demonstrates how to read NFC tags only when the application is in the foreground.
    • TagViewer demonstrates how to receive NFC tag intents even when the application is not running.
    • TagWriter demonstrates how to write to an NFC tag using the Ndef tag technology data format.
  • iOS example applications are located in the example/ios folder of the module:

    • TagViewer demonstrates how to receive NFC tags even when the application is running.

Examples

Creating NFC Adapter (iOS & Android)

This example demonstrates the proper technique for creating an NFC adapter. The NFC Adapter should be created after the window has been opened.

var nfc = require('ti.nfc');
var nfcAdapter = null;

$.index.addEventListener('open', function(e) {
    // Must wait until the activity has been opened before setting up NFC
    // Create the NFC adapter to be associated with this activity. 
    // There should only be ONE adapter created per activity.
    nfcAdapter = nfc.createNfcAdapter({
        onNdefDiscovered: handleDiscovery,
        onTagDiscovered: handleDiscovery, // Android-only
        onTechDiscovered: handleDiscovery // Android-only
    });

    // It's possible that the device does not support NFC. Check it here
    // before we go any further. For iOS, right now this is decided 
    // internally by the system. 
    if (OS_ANDROID) {
        if (!nfcAdapter.isEnabled()) {
            alert('NFC is not enabled on this device');
            return;
        }
        Ti.Android.currentActivity.addEventListener('newintent', function (e) {
            nfcAdapter.onNewIntent(e.intent);
        });
        
    // iOS needs to be told to scan
    } else if (OS_IOS) {
        nfcAdapter.begin();
    }
});

function handleDiscovery(e) {
    alert(JSON.stringify(e, null, 2));
}

$.index.open();

Properties 61

ACTION_NDEF_DISCOVERED

StringAndroidsince 1.0.0read-only

Intent to start an activity when a tag with NDEF payload is discovered.

ACTION_TAG_DISCOVERED

StringAndroidsince 1.0.0read-only

Intent to start an activity when a tag is discovered.

ACTION_TECH_DISCOVERED

StringAndroidsince 1.0.0read-only

Intent to start an activity when a tag is discovered and activities are registered for the specific technologies on the tag.

ENCODING_UTF16

StringAndroidsince 1.0.0read-only

Used with ndefRecord records.
Indicates UTF-16 text encoding.

ENCODING_UTF8

StringAndroidsince 1.0.0read-only

Used with ndefRecord records.
Indicates UTF-8 text encoding.

ERROR_SECURITY_VIOLATION

NumberiPhonesince 2.0.0read-only

A security violation associated with the reader session has occurred.

MIFARE_BLOCK_SIZE

NumberAndroidsince 1.1.0read-only

Used with TECH_MIFARE_CLASSIC tag technology. Size of a MIFARE CLassic block (in bytes).

MIFARE_SIZE_1K

NumberAndroidsince 1.1.0read-only

Used with TECH_MIFARE_CLASSIC tag technology. Tag contains 16 sectors, each with 4 blocks.

MIFARE_SIZE_2K

NumberAndroidsince 1.1.0read-only

Used with TECH_MIFARE_CLASSIC tag technology. Tag contains 32 sectors, each with 4 blocks.

MIFARE_SIZE_4K

NumberAndroidsince 1.1.0read-only

Used with TECH_MIFARE_CLASSIC tag technology. Tag contains 40 sectors.

MIFARE_SIZE_MINI

NumberAndroidsince 1.1.0read-only

Used with TECH_MIFARE_CLASSIC tag technology. Tag contains 5 sectors, each with 4 blocks.

MIFARE_TAG_TYPE_CLASSIC

NumberAndroidsince 1.1.0read-only

Used with TECH_MIFARE_CLASSIC tag technology. A MIFARE Classic tag.

MIFARE_TAG_TYPE_PLUS

NumberAndroidsince 1.1.0read-only

Used with TECH_MIFARE_CLASSIC tag technology. A MIFARE Plus tag.

MIFARE_TAG_TYPE_PRO

NumberAndroidsince 1.1.0read-only

Used with TECH_MIFARE_CLASSIC tag technology. A MIFARE Pro tag.

MIFARE_TAG_TYPE_UNKNOWN

NumberAndroidsince 1.1.0read-only

Used with TECH_MIFARE_CLASSIC tag technology. A MIFARE Classic compatible card of unknown type.

MIFARE_ULTRALIGHT_PAGE_SIZE

NumberAndroidsince 1.1.0read-only

Used with TECH_MIFARE_ULTRALIGHT tag technology. Size of a MIFARE Ultralight page (in bytes).

MIFARE_ULTRALIGHT_TYPE_UNKNOWN

NumberAndroidsince 1.1.0read-only

Used with TECH_MIFARE_ULTRALIGHT tag technology. A MIFARE Ultralight compatible tag of unknown type.

RTD_ALTERNATIVE_CARRIER

StringAndroidsince 1.0.0read-only

Used with ndefRecord records.
RTD Alternative Carrier type. For use with TNF_WELL_KNOWN.

RTD_HANDOVER_CARRIER

StringAndroidsince 1.0.0read-only

Used with ndefRecord records.
RTD Handover Carrier type. For use with TNF_WELL_KNOWN.

RTD_HANDOVER_REQUEST

StringAndroidsince 1.0.0read-only

Used with ndefRecord records.
RTD Handover Request type. For use with TNF_WELL_KNOWN.

RTD_HANDOVER_SELECT

StringAndroidsince 1.0.0read-only

Used with ndefRecord records.
RTD Handover Select type. For use with TNF_WELL_KNOWN.

RTD_SMART_POSTER

StringAndroidsince 1.0.0read-only

Used with ndefRecord records.
RTD Smart Poster type. For use with TNF_WELL_KNOWN.

RTD_TEXT

StringAndroidsince 1.0.0read-only

Used with ndefRecord records.
RTD Text type. For use with TNF_WELL_KNOWN.

RTD_URI

StringAndroidsince 1.0.0read-only

Used with ndefRecord records.
RTD URI type. For use with TNF_WELL_KNOWN.

TAG_TYPE_MIFARE_CLASSIC

StringAndroidsince 1.1.0read-only

Used with TECH_NDEF tag technology. NDEF on MIFARE Classic.

TECH_ISODEP

NumberAndroidsince 1.0.0read-only

Available tag technology used with getTechList and AdapterProxy.

TECH_MIFARE_CLASSIC

NumberAndroidsince 1.0.0read-only

Available tag technology used with getTechList and AdapterProxy.

TECH_MIFARE_ULTRALIGHT

NumberAndroidsince 1.0.0read-only

Available tag technology used with getTechList and AdapterProxy.

TECH_NDEF

NumberAndroidsince 1.0.0read-only

Available tag technology used with getTechList and AdapterProxy.

TECH_NDEFFORMATABLE

NumberAndroidsince 1.0.0read-only

Available tag technology used with getTechList and AdapterProxy.

TECH_NFCA

NumberAndroidsince 1.0.0read-only

Available tag technology used with getTechList and AdapterProxy.

TECH_NFCB

NumberAndroidsince 1.0.0read-only

Available tag technology used with getTechList and AdapterProxy.

TECH_NFCF

NumberAndroidsince 1.0.0read-only

Available tag technology used with getTechList and AdapterProxy.

TECH_NFCV

NumberAndroidsince 1.0.0read-only

Available tag technology used with getTechList and AdapterProxy.

TNF_ABSOLUTE_URI

Numbersince Android 1.0.0, iPhone 2.0.0read-only

Used with ndefRecord records. Indicates the type field contains an absolute-URI BNF construct defined by RFC 3986.

TNF_EMPTY

Numbersince Android 1.0.0, iPhone 2.0.0read-only

Used with ndefRecord records. Indicates the record is empty.

TNF_EXTERNAL_TYPE

Numbersince Android 1.0.0, iPhone 2.0.0read-only

Used with ndefRecord records. Indicates the type field contains an external type name.

TNF_MIME_MEDIA

Numbersince Android 1.0.0, iPhone 2.0.0read-only

Used with ndefRecord records.
Indicates the type field contains a media-type BNF construct, defined by RFC 2046.

TNF_UNCHANGED

Numbersince Android 1.0.0, iPhone 2.0.0read-only

Used with ndefRecord records.
Indicates the payload is an intermediate or final chunk of a chunked NDEF Record.

TNF_UNKNOWN

Numbersince Android 1.0.0, iPhone 2.0.0read-only

Used with ndefRecord records.
Indicates the payload type is unknown.

TNF_WELL_KNOWN

Numbersince Android 1.0.0, iPhone 2.0.0read-only

Used with ndefRecord records.
Indicates the type field contains a well-known RTD type name.

Methods 22

Modules.Nfc.MifareTagTechnology

proxyiPhonesince 1.1.0

Extends Modules.Nfc.NativeTagTechnologyTitanium.Proxy

Provides access to MIFARE Ultralight properties and I/O operations on a Modules.Nfc.NfcTag.

Use the Modules.Nfc.createTagTechnologyMifareUltralight method to create this tag technology. See also: Mifare Ultralight

Methods 7

The historical bytes extracted from an Answer To Select response.

The unique hardware identifier of the tag.

The MIFARE product family identifier for the tag.

Sends a native MIFARE command to the tag.

Parameters
ParametersTypeDescription
dataArray<Number>

hex command with length will be sent in form of data

errorCodeString

The error code; only present if an error occurred.

errorDomainString

The error domain; only present if an error occurred.

errorDescriptionString

The error description; only peresent if an error occurred.

Sends a native MIFARE command to the tag along with other parameter.

Parameters
ParametersTypeDescription
dataArray<Number>

hex command with length will be sent in form of data

sw1Number

The SW1 command-processing status byte.

sw2Number

The SW2 command-processing status byte.

apduTitanium.Buffer

An ISO 7816-4 command APDU object.

errorCodeString

The error code; only present if an error occurred.

errorDomainString

The error domain; only present if an error occurred.

errorDescriptionString

The error description; only peresent if an error occurred.

Modules.Nfc.NativeTagTechnology

proxyiPhonesince 1.1.0

Extends Titanium.Proxy

Native Tag Technology class will have the common methods.

Common methods get called for all the native tags so that we can save the redundancy of the code.

Methods 2

calls the connected to tag method for NFC Tag reader session.

if session is connected to any tag or not

Returns Boolean

provides if session is connected

Modules.Nfc.NdefMessage

proxyAndroidiPhonesince Android 1.0.0, iPhone 6.3.0

Extends Titanium.Proxy

Represents an immutable NDEF message.

Use the Modules.Nfc.createNdefMessage method to create an NDEF message.

See also: NdefMessage

Properties 1

Methods 1

Modules.Nfc.NdefRecord

proxyAndroidiPhonesince Android 1.0.0, iPhone 6.3.0

Extends Titanium.Proxy

Represents an immutable NDEF record.

Android: The NDEF record is the base type for more type-specific NDEF records. You will generally work with the type-specific NDEF records (e.g. NdefRecordText, NdefRecordUri, etc.) which have more applicable properties for each type of record.

Use one of the Modules.Nfc.createNdefRecordApplication, Modules.Nfc.createNdefRecordEmpty, Modules.Nfc.createNdefRecordExternal, Modules.Nfc.createNdefRecordMedia, Modules.Nfc.createNdefRecordSmartPoster, Modules.Nfc.createNdefRecordText, Modules.Nfc.createNdefRecordUnknown, or Modules.Nfc.createNdefRecordUri method variants to create an NDEF record.

iOS: The NFC-functionality is available on iOS 11 and later. It currently only allows to read specific NDEF-tags - writing tags is not supported by iOS so far.

See also: NdefRecord

Properties 6

hashCode

NumberAndroidread-only

The integer hash code for this object.

id

Stringread-only

The variable length ID.

tnf

Numberread-only

The 3-bit TNF.

type

Stringread-only

The variable length Type field.

Methods 5

Returns the integer hash code for this object.

Returns Number

Returns the variable length ID.

Returns String

Returns the record type.

This is the class name of the NDEF record (e.g. NdefRecordText)

Returns String

Returns the 3-bit TNF.

Returns Number

Returns the variable length Type field.

Returns String

Modules.Nfc.NdefRecordApplication

proxyAndroidsince 1.0.0

Extends Modules.Nfc.NdefRecordTitanium.Proxy

Represents an immutable NDEF record indicating the package that should be used to handle the entire NDEF message.

This record type was introduced in Android 4.0 (API level 14).

See also: createApplicationRecord

Properties 7

Methods 5

Modules.Nfc.NdefRecordEmpty

proxyAndroidsince 1.0.0

Extends Modules.Nfc.NdefRecordTitanium.Proxy

Represents an immutable NDEF record that is empty.

Properties 6

Methods 5

Modules.Nfc.NdefRecordExternal

proxyAndroidsince 1.0.0

Extends Modules.Nfc.NdefRecordTitanium.Proxy

Represents an immutable NDEF record containing external (application-specific) data.

See also: createExternal

Properties 8

domain

String

Domain name of issuing organization.

Methods 5

Modules.Nfc.NdefRecordMedia

proxyAndroidsince 1.0.0

Extends Modules.Nfc.NdefRecordTitanium.Proxy

Represents an immutable NDEF record containing MIME data.

See also: createMime

Properties 7

Methods 5

Modules.Nfc.NdefRecordSmartPoster

proxyAndroidsince 1.0.0

Extends Modules.Nfc.NdefRecordTitanium.Proxy

Represents an immutable NDEF record containing a Smart Poster message.

Properties 10

action

Number

Recommended action.

mimeType

String

A valid MIME type for the external resource.

title

String

Title for the Smart Poster.

uri

String

Uri for the external resource.

Methods 5

Modules.Nfc.NdefRecordText

proxyAndroidsince 1.0.0

Extends Modules.Nfc.NdefRecordTitanium.Proxy

Represents an immutable NDEF record containing text.

Properties 9

encoding

String

Encoding format. Default is ENCODING_UTF8 ("UTF-8");

Language code. Defaults to current locale.

Methods 5

Modules.Nfc.NdefRecordUnknown

proxyAndroidsince 1.0.0

Extends Modules.Nfc.NdefRecordTitanium.Proxy

Represents an immutable NDEF record containing an unknown data format.

Properties 6

Methods 5

Modules.Nfc.NdefRecordUri

proxyAndroidsince 1.0.0

Extends Modules.Nfc.NdefRecordTitanium.Proxy

Represents an immutable NDEF record containing a URI.

See also: createUri

Properties 7

uri

String

URI or URL.

Methods 5

Modules.Nfc.NfcAdapter

proxyAndroidiPhonesince 1.0.0

Extends Titanium.Proxy

Represents the local NFC adapter.

The NFC adapter gives you access to the features of the NFC device. The NFC adapter proxy is always associated with the activity that was the current activity when it was created. The NFC Adapter must be created after the activity has been opened. You can use the window open event to know when the activity has been opened.

Use the Modules.Nfc.createNfcAdapter method to create an NFC adapter.

See also: NfcAdapter

Examples

Foreground Dispatch (Android)

This example uses foreground dispatch to receive NDEF messages only when the application is in the foreground.

// Create the NFC adapter to be associated with this activity. 
// There should only be ONE adapter created per activity.
nfcAdapter = nfc.createNfcAdapter({
    onNdefDiscovered: handleDiscovery,
    onTagDiscovered: handleDiscovery,
    onTechDiscovered: handleDiscovery
});

// It's possible that the device does not support NFC. Check it here
// before we go any further.
if (!nfcAdapter.isEnabled()) {
    alert('NFC is not enabled on this device');
    return;
}

// All tag scans are received by the activity as a new intent. Each
// scan intent needs to be passed to the nfc adapter for processing.
var act = Ti.Android.currentActivity;
act.addEventListener('newintent', function(e) {
    nfcAdapter.onNewIntent(e.intent);
});

// To enable NFC dispatching only while the application is in the foreground,
// the application must signal the module whenever the application state changes.
act.addEventListener('resume', function(e) {
    nfcAdapter.enableForegroundDispatch(dispatchFilter);
});
act.addEventListener('pause', function(e) {
    nfcAdapter.disableForegroundDispatch();
});

// This application is only interested in receiving NFC messages while
// in the foreground. So the dispatch filter must be defined to identify
// what types of NFC messages to receive.
dispatchFilter = nfc.createNfcForegroundDispatchFilter({
    intentFilters: [
        { action: nfc.ACTION_NDEF_DISCOVERED, mimeType: 'text/plain' },
        { action: nfc.ACTION_NDEF_DISCOVERED, scheme: 'http', host: 'www.appcelerator.com' }
    ],
    techLists: [
        [ "android.nfc.tech.NfcF" ],
        [ "android.nfc.tech.Ndef" ],
        [ "android.nfc.tech.MifareClassic" ],
        [ "android.nfc.tech.NfcA" ]
    ]
});

Push Message (Android)

This example sets a default push message to send using Android Beam.

// Create the NFC adapter to be associated with this activity. 
// There should only be ONE adapter created per activity.
nfcAdapter = nfc.createNfcAdapter({});

// It's possible that the device does not support NFC. Check it here
// before we go any further.
if (!nfcAdapter.isNdefPushEnabled()) {
    alert('NFC is not enabled on this device');
    return;
}

// Set the default Ndef message to send when tapped
var textRecord = nfc.createNdefRecordText({
    text: "NDEF Push Sample"
});
var msg = nfc.createNdefMessage({
    records: [ textRecord ]
});
nfcAdapter.setNdefPushMessage(msg);

Push Message Callback (Android)

This example uses the push message callback to dynamically create the NDEF message as needed.

// Create the NFC adapter to be associated with this activity. 
// There should only be ONE adapter created per activity.
nfcAdapter = nfc.createNfcAdapter({
    onPushMessage: function() {
        if (sendText) {
            ndefRecord = nfc.createNdefRecordText({
                text: "Hello"
            });
        } else {
            ndefRecord = nfc.createNdefRecordUri({
                uri: "http://www.appcelerator.com"
            });
        }
        return nfc.createNdefMessage({
            records: [
                ndefRecord 
            ]
        });
    }
});

// It's possible that the device does not support NFC. Check it here
// before we go any further.
if (!nfcAdapter.isEnabled()) {
    alert('NFC is not enabled on this device');
    return;
}

Properties 8

onBeamPushUris

CallbackAndroidsince 1.2.0

Callback function used to dynamically generate one or more Uris to send using Android Beam.

The callback function must return an array of Uri(s) to be pushed. This method is only available on Android 4.0 (API 16) and above.

See also: [setBeamPushUrisCallback](http://developer.android.com/reference/android/nfc/NfcAdapter.html#setBeamPushUrisCallback(android.nfc.NfcAdapter.CreateBeamUrisCallback, android.app.Activity))

onNdefInvalidated

Callback<NdefInvalidated>iPhonesince 2.0.1

Callback function to execute when a session was invalidated (either errored by the system or cancelled by the user).

onPushComplete

CallbackAndroidsince 1.0.0

Callback function to execute on successful Android Beam operation.

This method is only available on Android 4.0 (API 14) and above.

See also: [setOnNdefPushCompleteCallback](http://developer.android.com/reference/android/nfc/NfcAdapter.html#setOnNdefPushCompleteCallback(android.nfc.NfcAdapter.OnNdefPushCompleteCallback, android.app.Activity, android.app.Activity...)) in the Android Developer Reference.

onPushMessage

CallbackAndroidsince 1.0.0

Callback function used to dynamically generated NDEF messsages to send using Android Beam.

The callback function must return an NDEF message to be used for the Android Beam operation. This method is only available on Android 4.0 (API 14) and above.

See also: [setNdefPushMessageCallback](http://developer.android.com/reference/android/nfc/NfcAdapter.html#setNdefPushMessageCallback(android.nfc.NfcAdapter.CreateNdefMessageCallback, android.app.Activity, android.app.Activity...)) in the Android Developer Reference.

Methods 9

disableForegroundNdefPush

Androidsince 1.0.0

Disable NDEF message push over P2P.

This method was deprecated in API level 14. Use setNdefPushMessage instead.

enableForegroundDispatch

Androidsince 1.0.0

Enable foreground dispatch to the current activity.

The foreground dispatch system allows an activity to intercept an intent and claim priority over other activities that handle the same intent. When using foreground dispatching, you must process the pause and resume events on the activity. See the Foreground Dispatch example for an example of enabling and disabling foreground dispatch during these events.

See also: [enableForegroundDispatch](http://developer.android.com/reference/android/nfc/NfcAdapter.html#enableForegroundDispatch(android.app.Activity, android.app.PendingIntent, android.content.IntentFilter[], java.lang.String[][]))

Parameters
ParametersTypeDescription
dispatchFilterModules.Nfc.NfcForegroundDispatchFilter

A filter specifying intent, intent filters and technology lists used to match dispatch intents.

enableForegroundNdefPush

Androidsince 1.0.0

Enable NDEF message push over P2P.

This method was deprecated in API level 14. Use setNdefPushMessage instead.

Parameters
ParametersTypeDescription
messageModules.Nfc.NdefMessage

An NDEF message to push over NFC.

isEnabled

Androidsince 1.0.0

Return true if this NFC Adapter has any features enabled.

Returns Boolean

isNdefPushEnabled

Androidsince 1.0.0

Return true if the NDEF Push (Android Beam) feature is enabled.

Returns Boolean

onNewIntent

Androidsince 1.0.0

Processes a new intent received by an application.

The NFC tag dispatch system will dispatch an intent to your application when it discovers a tag that matches your application's intent filters. Intents received by your application after it has started MUST be passed to this method in order to be processed and parsed for processing by your application. If the intent is recognized as an NFC action, this method will call your onNdefDiscovered, onTagDiscovered, or onTechDiscovered' callback with the parsed information. You should add an event listener to the current activity for the newintent` event in your application and call this method with the received intent.

Parameters
ParametersTypeDescription
intentTitanium.Android.Intent

The Android intent received by your application

setBeamPushUris

Androidsince 1.2.0

Set one or more Uris to send using Android Beam.

See also [setBeamPushUris](http://developer.android.com/reference/android/nfc/NfcAdapter.html#setBeamPushUris(android.net.Uri[], android.app.Activity))

Parameters
ParametersTypeDescription
UrisArray<String>

An array of Uri(s) to push over Android Beam.

setNdefPushMessage

Androidsince 1.0.0

Set a static Modules.Nfc.NdefMessage to send using Android Beam.

See also: [setNdefPushMessage](http://developer.android.com/reference/android/nfc/NfcAdapter.html#setNdefPushMessage(android.nfc.NdefMessage, android.app.Activity, android.app.Activity...))

Parameters
ParametersTypeDescription
messageModules.Nfc.NdefMessage

An NDEF message to push over NFC, or null to disable.

Modules.Nfc.NfcForegroundDispatchFilter

proxyAndroidsince 1.0.0

Extends Titanium.Proxy

A filter specifying intent, intent filters and technology lists used to match dispatch intents.

The Modules.Nfc.NfcAdapter.enableForegroundDispatch method is used to give priority to the foreground activity when dispatching a discovered tag to an application. This proxy is used to specify the intent, intent filters, and technology lists used to filter the dispatched intents. This proxy automatically creates the required pending intent and will create an intent for the current activity if one is not provided.

Use the Modules.Nfc.createNfcForegroundDispatchFilter method to create a foreground dispatch filter.

See also: enableForegroundDispatch

Examples

Foreground Dispatch filter

This example creates a dispatch filter used to filter NDEF messages that are of mime type 'text/plain' or URI from 'http://www.appcelerator.com'. Additionally, the filter will match tags with the specified technologies. The dispatch filter is then used when calling the enableForegroundDispatch API of the <Modules.Nfc.NfcAdapter> proxy.

dispatchFilter = nfc.createNfcForegroundDispatchFilter({
    intentFilters: [
        { action: nfc.ACTION_NDEF_DISCOVERED, mimeType: 'text/plain' },
        { action: nfc.ACTION_NDEF_DISCOVERED, scheme: 'http', host: 'www.appcelerator.com' }
    ],
    techLists: [
        [ "android.nfc.tech.NfcF", "android.nfc.tech.NfcA", "android.nfc.Ndef" ],
        [ "android.nfc.tech.Ndef" ],
        [ "android.nfc.tech.MifareClassic" ],
        [ "android.nfc.tech.NfcA" ]
    ]
});

// All tag scans are received by the activity as a new intent. Each
// scan intent needs to be passed to the nfc adapter for processing.
var act = Ti.Android.currentActivity;
act.addEventListener('newintent', function(e) {
    nfcAdapter.onNewIntent(e.intent);
});

// To enable NFC dispatching only while the application is in the foreground,
// the application must signal the module whenever the application state changes.
act.addEventListener('resume', function(e) {
    nfcAdapter.enableForegroundDispatch(dispatchFilter);
});
act.addEventListener('pause', function(e) {
    nfcAdapter.disableForegroundDispatch();
});

Properties 3

The intent to start the dispatch when matched.

This optional property allows you to override the default behavior for dispatching the intent. If an intent is not provided (the default behavior), then an intent based on the current activity is automatically created with a flag of FLAG_ACTIVITY_SINGLE_TOP.

intentFilters

Array<NfcIntentFilter>

The intent filters to override dispatching for, or null to always dispatch.

techLists

Array<Array<String>>

The tech lists used to perform matching for dispatching the ACTION_TECH_DISCOVERED intent.

Modules.Nfc.NfcNDEFTag

proxyiPhoneiPadsince 3.0.1

Extends Titanium.Proxy

An interface for interacting with an NDEF tag.

It provide the interface for NFC Data Exchange Format (NDEF) tag.

Methods 1

available

iPhone

A value that determines whether the NDEF tag is available in the current reader session.

Returns Number

Modules.Nfc.NfcNDEFTagTechnology

proxyiPhoneiPadsince 3.0.1

Extends Titanium.Proxy

Provides access to NDEF tag and I/O operations on a Modules.Nfc.NfcNDEFTag

Use the <Modules.Nfc.createTagTechNdef> method to create this NDEF tag technology.

Methods 5

Call to connect NfcNDEFTag from session NFCNDEFReaderSession, connection success or failure result in a didConnectTag event.

Returns void

Asks the reader session for the NDEF support status of the tag. Success/Failure result in a didQueryNDEFStatus event.

Returns void

Retrieves an NDEF message from the tag. Success/Failure result in a didReadNDEFMessage event.

Returns void

Changes the NDEF tag status to read-only, preventing future write operations. Success/Failure result in a didWriteLock event.

Returns void

Saves an NDEF message to a writable tag. Success/Failure result in a didWirteNDEFMessage event.

Returns void

Events 5

A event called when NFCNDEFReaderSession try to connect with NDEF tag

A tag stays connected until your app connects to a different tag or restarts polling. Connecting to a tag that is already connected has no effect.

Event properties
Event propertiesTypeDescription
errorCodeNumber

The error code.

errorDescriptionString

A string containing the localized description of the error.

errorDomainString

A string containing the error domain.

Asks the reader session for the NDEF support status of the tag.

Asks the reader session (NFCNDEFReaderSession) for the NDEF support status of the tag.

Event properties
Event propertiesTypeDescription
errorCodeNumber

The error code.

errorDescriptionString

A string containing the localized description of the error.

errorDomainString

A string containing the error domain.

statusNumber

Constants that indicate status for an NDEF tag.

capacityNumber

Indicates the maximum NDEF message size, in bytes, that you can store on the tag.

Retrieves an NDEF message from the tag.

Retrieves an NDEF message from the tag.

Event properties
Event propertiesTypeDescription
errorCodeNumber

The error code.

errorDescriptionString

A string containing the localized description of the error.

errorDomainString

A string containing the error domain.

messageModules.Nfc.NdefMessage

An NFC NDEF message consisting of an array of payload records.

Saves an NDEF message to a writable tag.

To determine whether the tag is writable, call queryNDEFStatus and check that the status is NFC_NDEF_READ_WRITE.

Event properties
Event propertiesTypeDescription
errorCodeNumber

The error code.

errorDescriptionString

A string containing the localized description of the error.

errorDomainString

A string containing the error domain.

Changes the NDEF tag status to read-only, preventing future write operations.

Calling this method updates the write access condition byte in the NDEF File Control of the tag's file system, thus locking the tag. This is a permanent action that you cannot undo. After locking the tag, you can no longer write data to it.

Event properties
Event propertiesTypeDescription
errorCodeNumber

The error code.

errorDescriptionString

A string containing the localized description of the error.

errorDomainString

A string containing the error domain.

Modules.Nfc.NfcTag

proxyAndroidiPhonesince 1.0.0

Extends Titanium.Proxy

Represents an NFC tag that has been discovered

See also: Tag

Properties 2

id

Stringread-only

Tag identifier (if it has one)

techList

Array<String>read-only

Technologies available in this tag, as fully qualified class names.

Methods 3

available

iPhone

Returns if the tag is available in current session

Returns Number

Returns the tag identifier (if it has one)

Returns String

Returns the technologies available in this tag, as fully qualified class names.

Returns Array<String>

Modules.Nfc.TagTechnology

proxyAndroidsince 1.1.0

Extends Titanium.Proxy

Represents an interface to a specific tag technology.

NFC tags are based on a number of independently developed technologies and offer a wide range of capabilities. The TagTechnology proxies provide access to these different technologies and capabilities. The TagTechnology proxy is the base type for more type-specific tag technologies. You will work with the type-specific tag technology proxies which provide capabilities for each tag technology.

Use one of the Modules.Nfc.createTagTechnologyIsoDep, Modules.Nfc.createTagTechnologyMifareClassic, Modules.Nfc.createTagTechnologyMifareUltralight, Modules.Nfc.createTagTechnologyNdefFormatable, Modules.Nfc.createTagTechnologyNdef, Modules.Nfc.createTagTechnologyNfcA, Modules.Nfc.createTagTechnologyNfcB, Modules.Nfc.createTagTechnologyNfcF, Modules.Nfc.createTagTechnologyNfcV method variants to create a tag technology proxy.

See also: TagTechnology

Examples

Write Ndef Tag

This example uses the TECH_NDEF tag technology to write a <Modules.Nfc.NdefMessage> message to a tag.

var tech = nfc.createTagTechnologyNdef({
    tag: scannedTag
});

if (!tech.isValid()) {
    alert("Failed to create Ndef tag type");
    return;
}

// Attempt to write an Ndef record to the tag
try {
    tech.connect();

    // It's possible that the tag is not writable, so we need to check first.
    if (!tech.isWritable()) {
        alert ("Tag is not writable");
    } else {
        // Create a new message to write to the tag
        var date = new Date();
        var textRecord = nfc.createNdefRecordText({
            text: "Titanium NFC module. Tag updated on " + date.toLocaleString() + "!!!"
        });
        var msg = nfc.createNdefMessage({
            records: [ textRecord ]
        });
    
        // Write to the tag
        tech.writeNdefMessage(msg);
    }
} catch (e) {
    alert("Error: " + e.message);
} finally {
    if (tech.isConnected()) {
        tech.close();
    }
}

Properties 1

Methods 4

Disable I/O operations to the tag and release resources.

Enable I/O operations to the tag.

Only one Tag Technology proxy can be connected to a Tag at a time.

Returns true if connect has completed, and close has not been called, and the tag is not known to be out of range.

Returns Boolean

Return true if this tag technology was successfully obtained.

Returns Boolean

Modules.Nfc.TagTechnologyIsoDep

proxyAndroidsince 1.1.0

Extends Modules.Nfc.TagTechnologyTitanium.Proxy

Provides access to ISO-DEP (ISO 14443-4) properties and I/O operations on a Modules.Nfc.NfcTag.

Use the Modules.Nfc.createTagTechnologyIsoDep method to create this tag technology.

See also: IsoDep

Properties 1

Methods 11

Get the current timeout for transceive in milliseconds.

Returns Number

Inherited from Modules.Nfc.TagTechnology

Returns true if connect has completed, and close has not been called, and the tag is not known to be out of range.

Returns Boolean

Set the timeout of transceive in milliseconds.

Parameters
ParametersTypeDescription
timeoutNumber

Timeout value in milliseconds

Modules.Nfc.TagTechnologyMifareClassic

proxyAndroidsince 1.1.0

Extends Modules.Nfc.TagTechnologyTitanium.Proxy

Provides access to MIFARE Classic properties and I/O operations on a Modules.Nfc.NfcTag.

Use the Modules.Nfc.createTagTechnologyMifareClassic method to create this tag technology.

See also: MifareClassic

Properties 4

Methods 23

Authenticate a sector with key A.

Parameters
ParametersTypeDescription
sectorIndexNumber

Index of sector to authenticate, starting from 0.

keyTitanium.Buffer

6-byte authentication key.

Returns Boolean

Returns true on success, false on authentication failure.

Authenticate a sector with key B.

Parameters
ParametersTypeDescription
sectorIndexNumber

Index of sector to authenticate, starting from 0.

keyTitanium.Buffer

6-byte authentication key.

Returns Boolean

Returns true on success, false on authentication failure.

Return the sector that contains a given block.

Parameters
ParametersTypeDescription
blockIndexNumber

Index of block to lookup, starting from 0.

Returns Number

Decrement a value block, storing the result in the temporary block on the tag.

Parameters
ParametersTypeDescription
blockIndexNumber

Index of block to decrement, starting from 0.

valueNumber

Non-negative to decrement by.

Return the total number of MIFARE Classic blocks.

Returns Number

Return the number of blocks in the given sector.

Parameters
ParametersTypeDescription
sectorIndexNumber

Index of sector, starting from 0.

Returns Number

Return the number of MIFARE Classic sectors.

Returns Number

Return the size of the tag in bytes.

Returns Number

Get the current transceive timeout in milliseconds.

Returns Number

Return the type of this MIFARE Classic compatible tag.

Returns Number

Increment a value block, storing the result in the temporary block on the tag.

Parameters
ParametersTypeDescription
blockIndexNumber

Index of block to increment, starting from 0.

valueNumber

Non-negative to increment by.

Inherited from Modules.Nfc.TagTechnology

Returns true if connect has completed, and close has not been called, and the tag is not known to be out of range.

Returns Boolean

Read 16-byte block.

Parameters
ParametersTypeDescription
blockIndexNumber

Index of block to read, starting from 0.

Returns Titanium.Buffer

16 byte block.

Copy from a value block to the temporary block.

Parameters
ParametersTypeDescription
blockIndexNumber

Index of block to copy from.

Return the first block of a given sector.

Parameters
ParametersTypeDescription
sectorIndexNumber

Index of sector to lookup, starting from 0.

Returns Number

Set the transceive timeout in milliseconds.

Parameters
ParametersTypeDescription
timeoutNumber

Timeout value in milliseconds.

Copy from the temporary block to a value block.

Parameters
ParametersTypeDescription
blockIndexNumber

Index of block to copy to.

Write 16-byte block.

Parameters
ParametersTypeDescription
blockIndexNumber

Index of block to write, starting from 0.

dataTitanium.Buffer

16 bytes of data to write.

Modules.Nfc.TagTechnologyMifareUltralight

proxyAndroidsince 1.1.0

Extends Modules.Nfc.TagTechnologyTitanium.Proxy

Provides access to MIFARE Ultralight properties and I/O operations on a Modules.Nfc.NfcTag.

Use the Modules.Nfc.createTagTechnologyMifareUltralight method to create this tag technology.

See also: MifareUltralight

Properties 1

Methods 11

Get the current transceive timeout in milliseconds.

Returns Number

Return the MIFARE Ultralight type of the tag.

One of MIFARE_ULTRALIGHT_TYPE_ULTRALIGHT, MIFARE_ULTRALIGHT_TYPE_ULTRALIGHT_C, or MIFARE_ULTRALIGHT_TYPE_UNKNOWN.

Returns Number

Inherited from Modules.Nfc.TagTechnology

Returns true if connect has completed, and close has not been called, and the tag is not known to be out of range.

Returns Boolean

Read 4 pages (16 bytes).

Parameters
ParametersTypeDescription
pageOffsetNumber

Index of first page to read, starting from 0.

Returns Titanium.Buffer

4 pages (16 bytes)

Set the transceive timeout in milliseconds.

Parameters
ParametersTypeDescription
timeoutNumber

Timeout value in milliseconds.

Write 1 page (4 bytes).

Parameters
ParametersTypeDescription
pageOffsetNumber

Index of page to write, starting from 0.

dataTitanium.Buffer

4 bytes to write.

Modules.Nfc.TagTechnologyNdef

proxyAndroidsince 1.1.0

Extends Modules.Nfc.TagTechnologyTitanium.Proxy

Provides access to NDEF content and operations on a Modules.Nfc.NfcTag.

Use the Modules.Nfc.createTagTechnologyNdef method to create this tag technology.

See also: Ndef

Properties 1

Methods 12

Indicates whether a tag can be made read-only with makeReadOnly.

Returns Boolean

true if it is possible to make this tag read-only.

Get the maximum NDEF message size in bytes.

Returns Number

Get the NDEF tag type.

One of TAG_TYPE_NFC_FORUM_TYPE_1, TAG_TYPE_NFC_FORUM_TYPE_2, TAG_TYPE_NFC_FORUM_TYPE_3, TAG_TYPE_NFC_FORUM_TYPE_4, TAG_TYPE_MIFARE_CLASSIC, or another NDEF tag type that has not yet been formalized in the Android API.

Returns String

Inherited from Modules.Nfc.TagTechnology

Returns true if connect has completed, and close has not been called, and the tag is not known to be out of range.

Returns Boolean

Determine if the tag is writable.

Returns Boolean

true if the tag is writable.

Make a tag read-only.

Returns Boolean

true on success, false if it is not possible to make this tag read-only.

Modules.Nfc.TagTechnologyNdefFormatable

proxyAndroidsince 1.1.0

Extends Modules.Nfc.TagTechnologyTitanium.Proxy

Provide access to NDEF format operations on a Modules.Nfc.NfcTag.

Use the Modules.Nfc.createTagTechnologyNdefFormatable method to create this tag technology.

See also: NdefFormatable

Properties 1

Methods 6

Inherited from Modules.Nfc.TagTechnology

Returns true if connect has completed, and close has not been called, and the tag is not known to be out of range.

Returns Boolean

Modules.Nfc.TagTechnologyNfcA

proxyAndroidsince 1.1.0

Extends Modules.Nfc.TagTechnologyTitanium.Proxy

Provides access to NFC-A (ISO 14443-3A) properties and I/O operations on a Modules.Nfc.NfcTag.

Use the Modules.Nfc.createTagTechnologyNfcA method to create this tag technology.

See also: NfcA

Properties 1

Methods 10

Return the SAK/SEL_RES bytes from tag discovery.

Returns Number

SAK bytes.

Get the current transceive timeout in milliseconds.

Returns Number

Inherited from Modules.Nfc.TagTechnology

Returns true if connect has completed, and close has not been called, and the tag is not known to be out of range.

Returns Boolean

Set the timeout of transceive in milliseconds.

Parameters
ParametersTypeDescription
timeoutNumber

Timeout value in milliseconds

Modules.Nfc.TagTechnologyNfcB

proxyAndroidsince 1.1.0

Extends Modules.Nfc.TagTechnologyTitanium.Proxy

Provides access to NFC-B (ISO 14443-3B) properties and I/O operations on a Modules.Nfc.NfcTag.

Use the Modules.Nfc.createTagTechnologyNfcB method to create this tag technology.

See also: NfcB

Properties 1

Methods 8

Return the Protocol Info bytes from ATQB/SENSB_RES at tag discovery.

Returns Titanium.Buffer

Protocol Info bytes from ATQB/SENSB_RES bytes.

Inherited from Modules.Nfc.TagTechnology

Returns true if connect has completed, and close has not been called, and the tag is not known to be out of range.

Returns Boolean

Modules.Nfc.TagTechnologyNfcF

proxyAndroidsince 1.1.0

Extends Modules.Nfc.TagTechnologyTitanium.Proxy

Provides access to NFC-F (JIS 6319-4) properties and I/O operations on a Modules.Nfc.NfcTag.

Use the Modules.Nfc.createTagTechnologyNfcF method to create this tag technology.

See also: NfcF

Properties 1

Methods 10

Get the current transceive timeout in milliseconds.

Returns Number

Inherited from Modules.Nfc.TagTechnology

Returns true if connect has completed, and close has not been called, and the tag is not known to be out of range.

Returns Boolean

Set the timeout of transceive in milliseconds.

Parameters
ParametersTypeDescription
timeoutNumber

Timeout value in milliseconds

Modules.Nfc.TagTechnologyNfcV

proxyAndroidsince 1.1.0

Extends Modules.Nfc.TagTechnologyTitanium.Proxy

Provides access to NFC-V (ISO 15693) properties and I/O operations on a Modules.Nfc.NfcTag.

Use the Modules.Nfc.createTagTechnologyNfcV method to create this tag technology.

See also: NfcV

Properties 1

Methods 8

Return the DSF ID bytes from tag discovery.

Returns Number

Return the Response Flag bytes from tag discovery.

Returns Number

Response Flag bytes.

Inherited from Modules.Nfc.TagTechnology

Returns true if connect has completed, and close has not been called, and the tag is not known to be out of range.

Returns Boolean

NdefDiscovered

pseudoAndroidiPhonesince 1.0.0

Argument passed to the callback when an NDEF message, tag, or technology is discovered.

Properties 4

action

StringAndroid

Identifies the action from the intent.

This value will be one of the constants defined on the Modules.Nfc module object (ACTION_NDEF_DISCOVERED, ACTION_TAG_DISCOVERED, or ACTION_TECH_DISCOVERED).

error

NumberiPhone

The error code returned if an error occurred while reading the tag.