iOS11 NFC 讀卡Demo
注意耿焊,NFC開(kāi)發(fā)現(xiàn)需要付費(fèi)開(kāi)發(fā)者才能使用
0x01 準(zhǔn)備工作
-
創(chuàng)建一個(gè)
App ID
,并勾選NFC Tag Reading
創(chuàng)建應(yīng)用享言,并使用剛才創(chuàng)建的
App ID
在
plist
文件中加入以下幾行
<key>NFCReaderUsageDescription</key>
<string>NFC Tag!</string>
- 生成
CardCollections.entitlements
在Capabilities
中打開(kāi)Push Notifications
然后關(guān)閉會(huì)生成一份工程名字.entitlements
,內(nèi)容填寫如下:
<?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
中設(shè)置Code Signing Entitlements
的路徑辫呻,務(wù)必保證路徑正確
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)")
}
}