I would like to scan the NDEF data from my NFC-Tag (NXP NTAG213) using the Core NFC framework introduced in iOS 11.
I succeeded to read the Payload within the tag:
TNF=1, Payload Type=<54>, Payload ID=<>, Payload=<026a61e3 8193e382 93e381ab e381a1e3 81af0a>
I'd like to extract the payload part, so here's what I've tried:
print("payload.payload")
but error occurred.
Here's my source code:
import UIKit
import CoreNFC
class ViewController: UIViewController, NFCNDEFReaderSessionDelegate{
var payloadData = "HaveNoData"
func readerSession(_ session: NFCNDEFReaderSession, didDetectNDEFs messages: [NFCNDEFMessage]) {
print("エラーは発生しませんでした")
for message in messages{
for payload in message.records {
print (payload)
payloadData = String(describing: payload.payload)
}
}
print(payloadData)
}
func readerSession(_ session: NFCNDEFReaderSession, didInvalidateWithError error: Error) {
print("Error: \(error.localizedDescription)")
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let session:NFCNDEFReaderSession = NFCNDEFReaderSession(delegate: self, queue: nil, invalidateAfterFirstRead: true)
session.begin()
}
@IBAction func launch(_ sender: Any) {
let session:NFCNDEFReaderSession = NFCNDEFReaderSession(delegate: self, queue: nil, invalidateAfterFirstRead: true)
session.begin()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
I'm not sure if you can use describing:
on payload.payload
here. But I believe the old-fashion String
from NSData
would work. (Not a daily Swift coder so not sure how it handles this these days with Swift 3/4).
In Objective-C, I can do it with:
NSString *dataString = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
or in your case NSUTF8StringEncoding
for the Japanese string.
Here's a sample project I made (in Objective-C).