NFC原理
NFC(Near Field Communication)即近距離無線通訊技術。該技術由飛利浦公司和索尼公司共同開發,可以在移動設備、消費類電子產品、PC 和智能控件工具間進行近距離無線通信。NFC提供了一種簡單、觸控式的解決方案,可以讓消費者簡單直觀地交換信息、訪問內容與服務。
NFC通信技術,允許電子設備之間進行非接觸式點對點數據傳輸(在十厘米內)交換數據。這個技術由免接觸式射頻識別(RFID)演變而來,并向下兼容RFID,主要用于手機等手持設備中提供M2M(Machine to Machine)的通信。由于近場通訊具有天然的安全性,因此,NFC技術被認為在手機支付等領域具有很大的應用前景。
什么是CoreNFC
CoreNFC是蘋果推出的支持NFC通訊的框架,僅支持裝有iOS 11的iPhone 7和iPhone 7Plus,Xcode 9 beta版。CoreNFC讀取的是NDEF標簽的數據。
怎么使用?首先,在你的開發者賬號里面添加上對NFC的支持:
其次,在你的XCode中添加TARGETS->Capabilities中打開Near Field Communication Tag Reading選項,XCode會自動幫你添加其他步驟
然后就是寫代碼啦
首先導入框架:
#import <CoreNFC/CoreNFC.h>
然后聲明一個NFCNDEFReaderSession對象:
@property (strong, nonatomic) NFCNDEFReaderSession *session;
NFCNDEFReaderSession對象初始化如下:
[self.session invalidateSession];
self.session = [[NFCNDEFReaderSession alloc] initWithDelegate:self
queue:nil
invalidateAfterFirstRead:NO];
if (NFCNDEFReaderSession.readingAvailable) {
self.session.alertMessage = @"把TAG放到手機背面";
[self.session beginSession];
} else {
[self showAlertMsg:@"此設備不支持NFC" title:@""];
}
然后實現NFCNDEFReaderSessionDelegate, NFCReaderSessionDelegate這兩個代理方法即可:
#pragma mark - NFCNDEFReaderSessionDelegate
- (void)readerSession:(NFCNDEFReaderSession *)session didInvalidateWithError:(NSError *)error{? ? // 讀取失敗? ?
?NSLog(@"%@",error);? ?
?if (error.code == 201) {? ? ? ? NSLog(@"掃描超時");? ? ? ?
?[self showAlertMsg:error.userInfo[NSLocalizedDescriptionKey] title:@"掃描超時"];? ?
?}? ? ? ?
?if (error.code == 200) {? ? ? ??
NSLog(@"取消掃描");? ? ??
? [self showAlertMsg:error.userInfo[NSLocalizedDescriptionKey] title:@"取消掃描"];? ??
}
}
- (void)readerSession:(NFCNDEFReaderSession *)session didDetectNDEFs:(NSArray*)messages
{
// 讀取成功
for (NFCNDEFMessage *msg in messages) {
NSArray *ary = msg.records;
for (NFCNDEFPayload *rec in ary) {
NFCTypeNameFormat typeName = rec.typeNameFormat;
NSData *payload = rec.payload;
NSData *type = rec.type;
NSData *identifier = rec.identifier;
NSLog(@"TypeName : %d",typeName);
NSLog(@"Payload : %@",payload);
NSLog(@"Type : %@",type);
NSLog(@"Identifier : %@",identifier);
}
}
[self.dataAry addObject:messages];
[self.tableView reloadData];
}
其中- (void)readerSession:(NFCNDEFReaderSession *)session didInvalidateWithError:(NSError *)error函數是為了報告掃描時發生的錯誤,- (void)readerSession:(NFCNDEFReaderSession *)session didDetectNDEFs:(NSArray*)messages是讀出結果時調用的函數,來進行數據的操作。