LoginSignup
1
0

More than 1 year has passed since last update.

CoreNFC使ってNFCタグのIDを取る方法

Last updated at Posted at 2022-11-17

はじめに

coreNFCではNFCタグのID(以下UID)を取得する関数が用意されていないのでなんとかして取り出しました。

取り出し方

以下のコードで取り出しました。
scanTagIDの中にUIDが保存されています。

func tagReaderSession(_ session: NFCTagReaderSession, didDetect tags: [NFCTag]) {
        session.connect(to: tag){ (error) in
        if nil != error{
            session.invalidate(errorMessage: "接続失敗")
        }
        if case let .miFare(sTag) = tag{
            let scanTagID = sTag.identifier.map{ String(format: "%.2hhx", $0)}.joined()
            print("UID:",scanTagID)  //UID:04a37ca2956482(example)
        }
}

仕組み

let scanTagID = sTag.identifier.map{ String(format: "%.2hhx", $0)}.joined()

この部分でUIDを引っ張ってきています。
mapsTag.identifierの中身をすべて文字列に変換しています。
数値のString変換

%.2hhxなので小数点以下2桁の16進数の1byte文字(一文字)に変換している?(ここの理解が曖昧)

変換指定子 変換データ型 詳細
%hhx char
unsigned char
16進数で読み込み、1Byte変数に変換
%.2 double 少数点以下2桁

変換指定子

備忘録map使い方

let ary1 = [1,2,3]
let ary2 = array.map { $0 * 2 } // すべての要素に*5
ary2 // [2, 4, 6]
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0