gpt4 book ai didi

iOS 11 核心 NFC - 任何示例代码?

转载 作者:IT王子 更新时间:2023-10-29 08:13:51 25 4
gpt4 key购买 nike

我刚刚在 iPhone 7 上安装了第一个 iOS 11 beta,并且有兴趣尝试 NFC。设置中没有关于它的任何内容。我想知道是否有任何示例代码显示如何读取标签。谁能在代码片段中展示如何使用 Core NFC SDK?

最佳答案

在 Apple Developer 站点中,创建一个新的 App ID 并确保启用NFC Tag Reading

Dev portal capabilities

将以下行添加到您的 .plist 文件中:

<key>NFCReaderUsageDescription</key>
<string>NFC Tag!</string>

并将这些添加到权利文件中:

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

在相应的文件中它应该看起来像这样:

enter image description here

也可以通过 Xcode 中的“功能”选项卡启用 Core NFC。

enter image description here

objective-c

导入CoreNFC

#import <CoreNFC/CoreNFC.h>

并设置委托(delegate):

@interface YourViewController : UIViewController <NFCNDEFReaderSessionDelegate>

在viewDidLoad中:

- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
NFCNDEFReaderSession *session = [[NFCNDEFReaderSession alloc] initWithDelegate:self queue:dispatch_queue_create(NULL, DISPATCH_QUEUE_CONCURRENT) invalidateAfterFirstRead:NO];
[session beginSession];
}

在委托(delegate)回调中:

- (void) readerSession:(nonnull NFCNDEFReaderSession *)session didDetectNDEFs:(nonnull NSArray<NFCNDEFMessage *> *)messages {

for (NFCNDEFMessage *message in messages) {
for (NFCNDEFPayload *payload in message.records) {
NSLog(@"Payload data:%@",payload.payload);
}
}
}

您还必须添加 didInvalidateWithError 委托(delegate)回调,否则您将不符合协议(protocol):

- (void)readerSession:(nonnull NFCNDEFReaderSession *)session didInvalidateWithError:(nonnull NSError *)error {

}

您可以通过以下方式停止阅读器:

[session invalidateSession];

swift 3/4

导入CoreNFC

import CoreNFC

并设置委托(delegate):

class YourViewController: UIViewController, NFCNDEFReaderSessionDelegate

在viewDidLoad中:

override func viewDidLoad() {
super.viewDidLoad()

let session = NFCNDEFReaderSession(delegate: self,
queue: DispatchQueue(label: "queueName", attributes: .concurrent), invalidateAfterFirstRead: false)
session?.begin()
}

在委托(delegate)回调中:

func readerSession(_ session: NFCNDEFReaderSession, didDetectNDEFs messages: [NFCNDEFMessage]) {
for message in messages {
for record in message.records {
print(record.payload)
}
}
}

您可以通过以下方式停止阅读器:

session.invalidateSession

用法

启动 View 后,您应该立即看到 iOS NFC 阅读器对话框,如下所示:

iOS NFC reader dialog

此对话框出现后,您有大约一秒钟的时间将 iPhone 放在您要读取的 NFC 标签附近。否则,该字段将被停用(这似乎是 Apple 端的一个错误)。我经常需要取消并重试以获得一致的读数。 More details here .

关于iOS 11 核心 NFC - 任何示例代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44380305/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com