iosios11xcode9-beta

CoreNFC debug not working


How programmatically work CoreNFC on xcode-9

func readerSession(_ session: NFCNDEFReaderSession, didInvalidateWithError error: Error) {
    //What I need to do here
}

func readerSession(_ session: NFCNDEFReaderSession, didDetectNDEFs messages: [NFCNDEFMessage]) {
    //What I need to do here
}

override func viewDidLoad() {
    super.viewDidLoad()

    let sessionReader = NFCNDEFReaderSession.init(delegate: self, queue: nil, invalidateAfterFirstRead: true)
    let nfcSession = NFCReaderSession.self

    let nfcTag = NFCTagCommandConfiguration.init()
    let tagType = NFCTagType(rawValue: 0)

    sessionReader.begin()

}

I want to know what I need to do for read some NFC tag.


Solution

  • There are four steps to get it working:

    1. Add the NFC Tag permission to your App Identifier in the Apple developer portal

    enter image description here

    1. Add a Code Signing Entitlement file to your project and build settings and add the following raw key and value:

    enter image description here enter image description here

    1. Add the usage description to your Info.plist:

    enter image description here

    1. Implement the delegate and pass it to the NFCNDEFReaderSession init like this:

      import UIKit
      import CoreNFC
      
      @UIApplicationMain
      class AppDelegate: UIResponder, UIApplicationDelegate, NFCNDEFReaderSessionDelegate {
      
          var window: UIWindow?
          var session: NFCNDEFReaderSession?
      
          func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
              session = NFCNDEFReaderSession(delegate: self, queue: nil, invalidateAfterFirstRead: false)
              self.session?.begin()
              return true
          }
      
          func readerSession(_ session: NFCNDEFReaderSession, didInvalidateWithError error: Error) {
              print(error)
          }
      
          func readerSession(_ session: NFCNDEFReaderSession, didDetectNDEFs messages: [NFCNDEFMessage]) {
              print(messages)
          }
      
      }