由于本人的工作和移动支付有关,所以一直对NFC技术比较关注。看到WWDC会议iOS 11开放了CoreNFC,赶紧了解一下。
使用NFC前需要注意一下几点:
需要开启一个session,与其他session类似,同时只能开启一个
需要App完全在前台模式
每个session最多扫描60s,超时需再次开启新session
配置读取单个或多个Tag,配置为单个时,会在读取到第一个Tag时自动结束session
隐私描述(后文会写到如何配置)会在扫描页面显示
在苹果开发者网站创建一个AppID, 并且确保NFC Tag Reading有效。
在.plist文件中加入以下项
NFCReaderUsageDescription We are going to use you NFC! com.apple.developer.nfc.readersession.formats NDEF
导入framework
#import
设置委托
@interface YourViewController : UIViewController
编辑代码viewDidLoad
- (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. NFCNDEFReaderSession *session = [[NFCNDEFReaderSession alloc] initWithDelegate:self queue:dispatch_queue_create(NULL, DISPATCH_QUEUE_CONCURRENT) invalidateAfterFirstRead:NO]; [session beginSession]; }
委托方法
- (void) readerSession:(nonnull NFCNDEFReaderSession *)session didDetectNDEFs:(nonnull NSArray*)messages { for (NFCNDEFMessage *message in messages) { for (NFCNDEFPayload *payload in message.records) { NSLog(@"Payload data:%@",payload.payload); } } }
在授权文件中加入key
com.apple.developer.nfc.readersession.formats NDEF
NFC Tag淘宝上可以买到,挺便宜的。
Android手机装个APP往Tag写入数据就可以开始测试了。
Apple什么时候可以真正开放NFC的卡模拟方式就好了。只是开放读卡器模式应用场景还是太受限了。