The following is a Java code example based on the Android platform, which implements the reading and writing functions of NFC tags and fully includes the core logic of NFC chip communication:
`import android.app.Activity;
import android.content.Intent;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.Ndef;
import android.nfc.tech.NdefFormatable;
import android.os.Bundle;
import android.widget.Toast;
public class NFCActivity extends Activity {
private NfcAdapter nfcAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
nfcAdapter = NfcAdapter.getDefaultAdapter(this);
if (nfcAdapter == null) {
Toast.makeText(this, "デバイスはNFCをサポートしていません", Toast.LENGTH_SHORT).show();
finish();
}
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
processNFCTag(tag);
}
private void processNFCTag(Tag tag) {
// NDEF形式データの読み取りを試行
Ndef ndef = Ndef.get(tag);
if (ndef != null) {
try {
ndef.connect();
if (ndef.isConnected()) {
byte[] payload = ndef.getNdefMessage().getRecords()[0].getPayload();
String content = new String(payload);
Toast.makeText(this, "読み取り内容:" + content, Toast.LENGTH_LONG).show();
}
ndef.close();
} catch (Exception e) {
Toast.makeText(this, "読み取り失敗:" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
} else {
// NDEF形式データの書き込みを試行
writeNFCTag(tag, "Hello NFC");
}
}
private void writeNFCTag(Tag tag, String data) {
NdefFormatable ndefFormat = NdefFormatable.get(tag);
if (ndefFormat != null) {
try {
ndefFormat.connect();
NdefRecord record = NdefRecord.createTextRecord("en", data);
NdefMessage message = new NdefMessage(new NdefRecord[]{record});
ndefFormat.format(message);
ndefFormat.close();
Toast.makeText(this, "書き込み成功", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(this, "書き込み失敗:" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
}
}`
The following is a complete iOS NFC example code, including read and write functions, suitable for iPhone devices that support NFC (such as iPhone 7 and above):
`import CoreNFC
class NFCManager: NSObject, NFCNDEFReaderSessionDelegate {
private var session: NFCNDEFReaderSession?
private var completion: ((String?) -> Void)?
func startReading(completion: @escaping (String?) -> Void) {
self.completion = completion
session = NFCNDEFReaderSession(
delegate: self,
queue: nil,
invalidateAfterFirstRead: false
)
session?.alertMessage = "iPhoneをNFCタグに近づけてください"
session?.begin()
}
func readerSession(_ session: NFCNDEFReaderSession, didDetectNDEFs messages: [NFCNDEFMessage]) {
var result = ""
for message in messages {
for record in message.records {
if let payload = String(data: record.payload, encoding: .utf8) {
result += payload + "\n"
}
}
}
completion?(result)
session.invalidate()
}
func readerSession(_ session: NFCNDEFReaderSession, didInvalidateWithError error: Error) {
completion?(nil)
print("NFCセッションエラー: \(error.localizedDescription)")
}
func writeToTag(data: String, completion: @escaping (Bool) -> Void) {
session = NFCNDEFReaderSession(
delegate: self,
queue: nil,
invalidateAfterFirstRead: true
)
session?.alertMessage = "空白のNFCタグにiPhoneを近づけてください"
session?.begin()
// タグ検出後の処理
self.completion = { content in
if content != nil {
completion(true)
} else {
completion(false)
}
}
}
// ビューコントローラでの使用例
func demoNFC() {
let manager = NFCManager()
// NFCタグ読み取り
manager.startReading { content in
if let content = content {
print("読み取り内容: \(content)")
} else {
print("読み取り失敗")
}
}
// NFCタグ書き込み(物理的な空白タグが必要)
manager.writeToTag(data: "Hello iOS NFC") { success in
if success {
print("書き込み成功")
} else {
print("書き込み失敗")
}
}
}
}
// Info.plistに追加:
// NFCReaderUsageDescription
// NFCタグへのアクセスが必要です(データの読み取り/書き込み)
// UISupportedExternalAccessoryProtocols
//
// com.apple.nfc.reader
//
`
Technical Support: https://www.tjnftagging.com
Top comments (0)