iOS11 NFC 读卡Demo
注意,NFC开发现需要付费开发者才能使用
0x01 准备工作
-
创建一个
App ID
,并勾选NFC Tag Reading
-
创建应用,并使用刚才创建的
App ID
-
在
plist
文件中加入以下几行
<key>NFCReaderUsageDescription</key>
<string>NFC Tag!</string>
- 生成
CardCollections.entitlements
在Capabilities
中打开Push Notifications
然后关闭会生成一份工程名字.entitlements
,内容填写如下:
<?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>NDEF</string>
</array>
</dict>
</plist>
然后前往Build Settings
中设置Code Signing Entitlements
的路径,务必保证路径正确
0x02 编写代码
import UIKit
import CoreNFC
class ViewController: UIViewController {
var session: NFCNDEFReaderSession!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
session = NFCNDEFReaderSession(delegate: self,
queue: DispatchQueue(label: "queueName", attributes: .concurrent), invalidateAfterFirstRead: false)
session.begin()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension ViewController: NFCNDEFReaderSessionDelegate {
func readerSession(_ session: NFCNDEFReaderSession, didDetectNDEFs messages: [NFCNDEFMessage]) {
for message in messages {
for record in message.records {
print(record.payload)
}
}
}
func readerSession(_ session: NFCNDEFReaderSession, didInvalidateWithError error: Error) {
print("read error:\(error)")
}
}
网友评论