Xamarin 中的 Core NFCCore NFC in Xamarin.iOS

使用 iOS 11 读取近现场通信(NFC)标记Reading Near Field Communication (NFC) tags using iOS 11

CoreNFC 是 iOS 11 中的一个新框架,可用于访问_近现场通信_(NFC)广播以从应用内部读取标记。CoreNFC is a new framework in iOS 11 that provides access to the Near Field Communication (NFC) radio to read tags from within apps. 它适用于 iPhone 7、7 +、8、8 Plus 和 X。It works on iPhone 7, 7 Plus, 8, 8 Plus, and X.

IOS 设备中的 NFC 标记读取器支持所有 NFC 标记类型1到5,其中包含_Nfc 数据交换格式_(NDEF)信息。The NFC tag reader in iOS devices supports all NFC tag types 1 through 5 that contain NFC Data Exchange Format (NDEF) information.

存在一些需要注意的限制:There are some restrictions to be aware of:

  • CoreNFC 仅支持标记读取(不写入或设置格式)。CoreNFC only supports tag reading (not writing or formatting).
  • 标记扫描必须是用户启动的,并且在60秒后超时。Tag scans must be user-initiated, and time-out after 60 seconds.
  • 应用必须在前台可见,以便进行扫描。Apps must be visible in the foreground for scanning.
  • CoreNFC 只能在实际设备上进行测试(而不是在模拟器上)。CoreNFC can only be tested on real devices (not on the simulator).

本页介绍使用 CoreNFC 所需的配置,并演示如何使用"NFCTagReader" 示例代码This page describes the configuration required to use CoreNFC and shows how to use the API using the "NFCTagReader" sample code.

配置Configuration

若要启用 CoreNFC,必须在项目中配置三个项:To enable CoreNFC, you must configure three items in your project:

  • Info.plist密钥。An Info.plist privacy key.
  • Info.plist项。An Entitlements.plist entry.
  • 具有NFC 标记读取功能的预配配置文件。A provisioning profile with NFC Tag Reading capability.

Info.plistInfo.plist

添加NFCReaderUsageDescription的隐私密钥和文本,在扫描发生时向用户显示该密钥和文本。Add the NFCReaderUsageDescription privacy key and text, which is displayed to the user while scanning is occurring. 使用适用于应用程序的消息(例如,说明扫描的用途):Use a message appropriate for your application (for example, explain the purpose of the scan):

<key>NFCReaderUsageDescription</key>
<string>NFC tag to read NDEF messages into the application</string>

Entitlements.plistEntitlements.plist

您的应用程序必须在您的权利中使用以下键/值对,请求近字段通信标记读取功能 。 info.plistYour app must request the Near Field Communications Tag Reading capability using the following key/value pair in your Entitlements.plist:

<key>com.apple.developer.nfc.readersession.formats</key>
<array>
  <string>NDEF</string>
</array>

设置配置文件Provisioning Profile

创建新的应用 ID ,并确保NFC 标记读取服务为勾选:Create a new App ID and ensure that the NFC Tag Reading service is ticked:

开发人员门户新建应用 ID "页,其中包含所选的 NFC 标记Developer Portal New App ID page with NFC Tag Reading selected

然后,你应该为此应用 ID 创建新的预配配置文件,然后将其下载并安装到你的开发 Mac 上。You should then create a new provisioning profile for this App ID, then download and install it on your development Mac.

读取标记Reading a Tag

配置项目后,将 using CoreNFC; 添加到文件顶部,然后执行以下三个步骤来实现 NFC 标记读取功能:Once your project is configured, add using CoreNFC; to the top of the file and follow these three steps to implement NFC tag reading functionality:

1. 实现 INFCNdefReaderSessionDelegate1. Implement INFCNdefReaderSessionDelegate

接口具有两个要实现的方法:The interface has two methods to be implemented:

  • DidDetect –当标记成功读取时调用。DidDetect – Called when a tag is successfully read.
  • DidInvalidate –当发生错误或达到60秒超时时调用。DidInvalidate – Called when an error occurs or the 60 second timeout is reached.

DidDetectDidDetect

在示例代码中,每个已扫描的消息都添加到表视图中:In the sample code, each scanned message is added to a table view:

public void DidDetect(NFCNdefReaderSession session, NFCNdefMessage[] messages)
{
    foreach (NFCNdefMessage msg in messages)
    {  // adds the messages to a list view
        DetectedMessages.Add(msg);
    }
    DispatchQueue.MainQueue.DispatchAsync(() =>
    {
        this.TableView.ReloadData();
    });
}

如果会话允许多个标记读取,则可以多次调用此方法(并且可以传入消息的数组)。This method may be called multiple times (and an array of messages may be passed in) if the session allows for multiple tag reads. 这是使用 Start 方法的第三个参数设置的(在步骤 2中介绍)。This is set using the third parameter of the Start method (explained in step 2).

DidInvalidateDidInvalidate

可能有多种原因会导致无效:Invalidation can occur for a number of reasons:

  • 扫描时出错。An error occurred while scanning.
  • 应用程序不再处于前台。The app ceased to be in the foreground.
  • 用户选择取消扫描。The user chose to cancel the scan.
  • 此扫描已被应用取消。The scan was cancelled by the app.

下面的代码演示如何处理错误:The code below shows how to handle an error:

public void DidInvalidate(NFCNdefReaderSession session, NSError error)
{
    var readerError = (NFCReaderError)(long)error.Code;
    if (readerError != NFCReaderError.ReaderSessionInvalidationErrorFirstNDEFTagRead &&
        readerError != NFCReaderError.ReaderSessionInvalidationErrorUserCanceled)
    {
      // some error handling
    }
}

会话失效后,必须创建新的会话对象以再次扫描。Once a session has been invalidated, a new session object must be created to scan again.

2. 启动 NFCNdefReaderSession2. Start an NFCNdefReaderSession

扫描应以用户请求开始,如按钮按下。Scanning should start with a user request, such as a button press. 下面的代码创建并启动一个扫描会话:The following code creates and starts a scanning session:

Session = new NFCNdefReaderSession(this, null, true);
Session?.BeginSession();

NFCNdefReaderSession 构造函数的参数如下所示:The parameters for the NFCNdefReaderSession constructor are as follows:

  • delegateINFCNdefReaderSessionDelegate的实现。delegate – An implementation of INFCNdefReaderSessionDelegate. 在示例代码中,委托是在表视图控制器中实现的,因此 this 用作委托参数。In the sample code, the delegate is implemented in the table view controller, therefore this is used as the delegate parameter.
  • queue –处理回调的队列。queue – The queue that callbacks are handled on. 它可以 null,在这种情况下,请务必在更新用户界面控件时使用 DispatchQueue.MainQueue (如示例中所示)。It can be null, in which case be sure to use the DispatchQueue.MainQueue when updating user interface controls (as shown in the sample).
  • invalidateAfterFirstRead –当 true时,扫描将在第一次成功扫描后停止;如果 false 扫描将继续,并返回多个结果,直到取消扫描或达到60秒超时。invalidateAfterFirstRead – When true, the scan stops after the first successful scan; when false scanning will continue and multiple results returned until the scan is cancelled or the 60 second timeout is reached.

3. 取消扫描会话3. Cancel the scanning session

用户可以通过用户界面中系统提供的按钮取消扫描会话:The user can cancel the scanning session via a system-provided button in the user-interface:

扫描时的 "取消" 按钮

应用可以通过调用 InvalidateSession 方法以编程方式取消扫描:The app can programmatically cancel the scan by calling the InvalidateSession method:

Session.InvalidateSession();

在这两种情况下,都将调用委托的 DidInvalidate 方法。In both cases, the delegate's DidInvalidate method will be called.

总结Summary

CoreNFC 使应用能够从 NFC 标记读取数据。CoreNFC enables your app to read data from NFC tags. 它支持读取各种标记格式(NDEF 类型1到5),但不支持写入或格式设置。It supports reading a variety of tag formats (NDEF types 1 through 5), but does not support writing or formatting.