iOS NFC功能開發


一、NDEF格式的

使用 NFCNDEFReaderSession。Delegate為:NFCNDEFReaderSessionDelegate

1、初始化對象

@property(strong,nonatomic)NFCNDEFReaderSession *session;

@property(strong,nonatomic)id<NFCNDEFTag> cuurentTag;

self.session = [[NFCNDEFReaderSession alloc]initWithDelegate:self queue:nil invalidateAfterFirstRead:YES]; //YES為只讀一個TAG然后結束,NO為讀取多個

self.session.alertMessage = @"讀取卡片,請將卡片靠近手機";

[self.session beginSession]; //開始識別 彈出識別提示框

代理方法

-(void)readerSession:(NFCNDEFReaderSession *)session didDetectTags:(NSArray<__kindof id<NFCNDEFTag>> *)tags API_AVAILABLE(ios(13.0)){

  self.cuurentTag = [tags firstObject];

}

識別到卡片后會回調該方法,在該方法中可獲取到tag。

2、讀取卡片內容:獲取到卡ID均為空,獲取卡ID需要下面第二種方法。

2.1 需要先建立連接

[_session connectToTag:self.cuurentTag completionHandler:^(NSError * _Nullable error) { }];

2.2連接成功之后調用方法,可以獲取到卡片的內容

[tag readNDEFWithCompletionHandler:^(NFCNDEFMessage *ndefMessage, NSError *error) { }];

3、寫入NDEF內容

3.1 需要先建立連接

[_session connectToTag:self.cuurentTag completionHandler:^(NSError * _Nullable error) { }];

3.2連接成功之后調用方法獲取卡片狀態:判斷是否可以寫入

[self.cuurentTag queryNDEFStatusWithCompletionHandler:^(NFCNDEFStatus status, NSUInteger capacity, NSError * _Nullable error) {}];

狀態 status == NFCNDEFStatusReadWrite 則可以寫入。

3.3 寫入

[self.cuurentTag writeNDEF:myMessage completionHandler:^(NSError * _Nullable error) {}];

二、iOS13新支持的類型:NFCPollingISO14443  NFCPollingISO15693  NFCPollingISO15693

使用NFCTagReaderSession。Delegate為:NFCTagReaderSessionDelegate

1.初始化對象

self.session = [[NFCTagReaderSession alloc]

                    initWithPollingOption:(NFCPollingISO14443 | NFCPollingISO15693 | NFCPollingISO15693) delegate:self queue:dispatch_get_main_queue()];

self.session.alertMessage = @"讀取卡片,請將卡片靠近手機";

[self.session beginSession]; //開始識別 彈出識別提示框

代理方法

-(void)tagReaderSession:(NFCTagReaderSession *)session  didDetectTags:(NSArray<__kindof id<NFCTag>> *)tags{

  self.cuurentTag = [tags firstObject];

}

2、讀取id(判斷卡類型,以下以其中一種為例),內容獲取方法同上

if (self.currentTag.type == NFCTagTypeMiFare) {

        id<NFCMiFareTag> mifareTag = [self.currentTag asNFCMiFareTag];

    NSData *data = mifareTag.identifier

}

3.寫入方法同上使用的tag需要為具體類型的tag,如:NFCMiFareTag

[mifareTag writeNDEF:ndefMsg completionHandler:^(NSError * error) { }];

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM