iOS11 Core NFC
iPhone6開始支持NFC(Near Field Communication
),但是最近蘋果最近(才)開放了NFC的部分接口。
可以實現檢測NFC標簽(NFC tags)并讀取包含NDEF(NFC Data Exchange Format)數據。
最起碼能當讀卡器玩了吧。
概述
Core NFC
可以讀取NFC tags,提供給用戶有關其物理環境和實體對象的更多信息。例如,小明在逛商場,他可以通過應用程序的NFC功能獲取到一些相關的商品信息。
Note
讀取NFC NDEF tag
當前只支持iPhone7/7+
使用Core NFC,您可以讀取符合NFC數據交換格式(NDEF)的五種標簽(type1到5)。
想要閱讀標簽,需要創建一個NFCNDEFReaderSession
的實例并設置代理。session會對NFC標簽進行輪詢,當找到NDEF
的消息時,會通過代理回調。代理收到消息后會,我們將session置為invalid([session invalidateSession]
).
實現
調試環境 Xcode9 beta + iPhone7
需要注意的CoreNFC當前沒有X86的版本,需要真機調試,否則報錯。。。 (Xcode9正式版沒有這個問題)
2017060763145coreNFC.png
-
新建AppleId,勾選
NFC Tag Reading
2017060729452.png -
新建工程配置好BundleId,與AppleId相匹配。添加20170607628875.png
-
info.plist添加
<key>NFCReaderUsageDescription</key> <string>We are going to use you NFC!</string>
-
.entitlements
文件添加內容: (Xcode9正式版,直接勾選target->Capabilities->Near Field Communication Tag Reading即可)<key>com.apple.developer.nfc.readersession.formats</key> <array> <string>NDEF</string> </array>
20170607123073.png20170607170904.png 代碼實現比較簡單
#import <CoreNFC/CoreNFC.h>
@interface ViewController ()<NFCNDEFReaderSessionDelegate>
@end
@implementation ViewController
- (IBAction)clicked:(id)sender {
NFCNDEFReaderSession *session = [[NFCNDEFReaderSession alloc] initWithDelegate:self queue:nil invalidateAfterFirstRead:NO];
//NSLog(@" ready ? %@", @([session isReady]));
[session beginSession];
}
#pragma mark - NFCNDEFReaderSessionDelegate
- (void) readerSession:(nonnull NFCNDEFReaderSession *)session didDetectNDEFs:(nonnull NSArray<NFCNDEFMessage *> *)messages {
for (NFCNDEFMessage *message in messages) {
for (NFCNDEFPayload *payload in message.records) {
NSLog(@"Payload data:%@",payload.payload);
//[session invalidateSession];
dispatch_async(dispatch_get_main_queue(), ^{
self.showingLabel.text = [[NSString alloc]initWithData:payload.payload encoding:NSUTF8StringEncoding];
});
}
}
}
- (void)readerSession:(NFCNDEFReaderSession *)session didInvalidateWithError:(NSError *)error{
NSLog(@"%@",error);
}
-
運行
2017060793692img.png
ok,先這樣了。 明天用公司的卡片試試。。
// ---更新 6.9
在iPhone7上做測試,發現直到超時都沒有讀取出到數據,項目配置沒檢查出問題。
懷疑是否是卡片的原因?
或者等出iOS11正式出了,在進行測試吧
--- 更新 2017-09-21
iOS11正式版出來了,現在能讀取到NFC標簽中的數據了
參考
https://developer.apple.com/documentation/corenfc
https://stackoverflow.com/questions/44380305/ios-11-core-nfc-any-sample-code