美文网首页
iOS11 NFC 读卡Demo

iOS11 NFC 读卡Demo

作者: xnxin | 来源:发表于2017-06-12 17:56 被阅读82次

    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)")
        }
    }
    

    相关文章

      网友评论

          本文标题:iOS11 NFC 读卡Demo

          本文链接:https://www.haomeiwen.com/subject/bpzlqxtx.html