Skip to content

Instantly share code, notes, and snippets.

@myrickchow32
Last active December 27, 2018 14:49
Show Gist options
  • Save myrickchow32/21ce6c80892d7778eb535147e94e2842 to your computer and use it in GitHub Desktop.
Save myrickchow32/21ce6c80892d7778eb535147e94e2842 to your computer and use it in GitHub Desktop.
import UIKit
// Step 1: Import CoreNFC library
import CoreNFC
class ViewController: UIViewController {
// Step 2: Hold a reference to the NFCNDEFReaderSession object as long as the ViewController stays alive.
var nfcSession: NFCNDEFReaderSession?
@IBAction func scanNFCDemoAction(_ sender: Any) {
startNFC(alertMessage: "Please scan a NFC tag.")
}
func startNFC(alertMessage: String) {
// Step 3: Check whether the current device can support NFC tag reading.
if !NFCNDEFReaderSession.readingAvailable {
showAlert()
return
}
/*
Step 4: Initialize NFCNDEFReaderSession object with parameter
invalidateAfterFirstRead:
true: NFCNDEFReaderSession will be automatically invalidated after the didDetectNDEFs() callback get fired and the blue-tick completion animation is finished.
Any manual invalidation of NFCNDEFReaderSession within didDetectNDEFs() callback will be IGNORED.
false: NFCNDEFReaderSession will be manually invalidated by developer.
Thus, it is possible to scan multiple NFC tags at the same time.
*/
nfcSession = NFCNDEFReaderSession.init(delegate: self, queue: nil, invalidateAfterFirstRead: true)
// Step 5: alert message is the string shown below the scan logo. The max number of line is 3.
// It is not possible to use an attributed string at the alertMessage property.
nfcSession?.alertMessage = alertMessage
// Step 6: To show the NFC reader dialog by beginning the NFC session
nfcSession?.begin()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment