Working with NFC
Contents
Near Field Communication (or NFC) is a relatively modern technology that allows mobile devices to interact with terminals, swipe cards and fobs.
Android and iOS 11 have support to give access to turn the phone into an NFC reader. With this detail you can send that data back to Sailthru Mobile as Custom Attributes, and use these for audiences and automation.iOS
CoreNFC was released in iOS 11 and Xcode 9. In the callback of the CoreNFC class, decode the payload and send relevant data to Sailthru Mobile. Note: Only NDEF formatted cards and devices can be read.Objective-C
- (void)readerSession:(NFCNDEFReaderSession *)session didDetectNDEFs:(NSArray<NFCNDEFMessage *> *)messages API_AVAILABLE(ios(11.0)) {
for (NFCNDEFMessage *message in messages) {
for (NFCNDEFPayload *record in message.records) {
NSLog(@"%@", record.payload);
NSString *optIdentifier = [NSString stringWithUTF8String:[record.identifier bytes]];
if (optIdentifier) {
STMAttributes *attrs = [STMAttributes new];
[attrs setString:optIdentifier forKey:"NFC_ID"];
[[SailthruMobile new] setAttributes:attrs withResponse:nil];
}
}
}
}
Swift
@available(iOS 11.0, *)
func readerSession(_ session: NFCNDEFReaderSession, didDetectNDEFs messages: [NFCNDEFMessage]) {
for message in messages {
for record in message.records {
print(record.payload)
let optIdentifier = String(bytes: record.identifier, encoding: .utf8)
if let identifier = optIdentifier {
let attrs = STMAttributes()
attrs.setString(identifier, forKey: "NFC_ID")
SailthruMobile().setAttributes(attrs, withResponse: nil)
}
}
}
}
Android
On Android, the NFC library will fire an intent where you'll be able to decode the payload. Similar to iOS, you should send the data to Sailthru Mobile from there.Java
// From the NFC Basics doc.
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
...
if (intent != null && NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())) {
Parcelable[] rawMessages =
intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
if (rawMessages != null) {
NdefMessage[] messages = new NdefMessage[rawMessages.length];
for (int i = 0; i < rawMessages.length; i++) {
messages[i] = (NdefMessage) rawMessages[i];
}
// Process the messages array.
// Send to Sailthru Mobile.
}
}
}
Kotlin
// From the NFC Basics doc.
override fun onNewIntent(intent: Intent?) {
super.onNewIntent(intent)
if (intent != null && NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.action)) {
val rawMessages: Array<Parcelable>? = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES)
if (rawMessages != null) {
val messages: Array<NdefMessage?> = arrayOfNulls(rawMessages.size)
for (i in rawMessages.indices) {
messages[i] = rawMessages[i] as NdefMessage
}
// Process the messages array.
// Send to Sailthru Mobile.
}
}
}