iOS11 NFC 读卡Demo

iOS11 NFC 读卡Demo

注意,NFC开发现需要付费开发者才能使用


0x01 准备工作

  • 创建一个App ID,并勾选NFC Tag Reading

    iOS11 NFC 读卡Demo_第1张图片

  • 创建应用,并使用刚才创建的App ID

  • plist文件中加入以下几行

NFCReaderUsageDescription
NFC Tag!
  • 生成CardCollections.entitlements
    Capabilities中打开Push Notifications然后关闭会生成一份工程名字.entitlements,内容填写如下:




    com.apple.developer.nfc.readersession.formats
    
        NDEF
    


然后前往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)")
    }
}

你可能感兴趣的:(iOS11 NFC 读卡Demo)