iOS 11 Core NFC使用详解

一.环境

系统:iOS 11+;(现在还没推送,可以使用iTunes通过固件升级);

开发工具:Xcode9.0+;

iOS11固件跟Xcode9.0测试版下载地址 https://developer.apple.com/download/

支持机型:iPhone7 ,iPhone7P;

二.配置项目

1.进入开发者中心设置AppID支持NFC Tag Reading,并且设置项目的Bundle Identifier跟新设置的AppID同步.

iOS 11 Core NFC使用详解_第1张图片
设置AppID

2.创建 .entitlements 文件(可以直接创建,也可以到target->capabilities里面打开任意开关,.entitlements文件会自动创建)。

iOS 11 Core NFC使用详解_第2张图片
创建 .entitlements 文件

右键 .entitlements文件点击  “Open As Source Code” 添加以下代码:

添加成功后entitlements文件显示如下:

然后在Info.plist文件中添加"Privacy - NFC Scan Usage Description"权限,当使用NFC时,将向用户显示此消息.

三.使用

导入 CoreNFC.h (只有在真机导入才不报错)

遵循协议 NFCNDEFReaderSessionDelegate

@property (nonatomic, strong) NFCNDEFReaderSession *ndefSession;

//床架会话

- (void)creatReader {        

self.ndefSession = [[NFCNDEFReaderSession alloc] initWithDelegate:self queue:nil invalidateAfterFirstRead:NO];     

   [_ndefSession beginSession];   

 }

//代理获取传输的信息

- (void)readerSession:(NFCNDEFReaderSession *)session didDetectNDEFs:(NSArray*)messages

{

NSLog(@"Called: %s", __func__);

for(NFCNDEFMessage *message in messages)

{

for(NFCNDEFPayload *payload in message.records)

{

NSLog(@"TNF:%d", payload.typeNameFormat);

NSLog(@"Type: %@", payload.type.description);

NSLog(@"payload: %@", payload.payload.description);

dispatch_async(dispatch_get_main_queue(),^{

NSString *str =[NSString stringWithFormat:@"TNF: %d\nType: %@\nPayload: %@", payload.typeNameFormat, payload.type.description, payload.payload.description];

});

}

}

}

//获取错误信息

- (void)readerSession:(NFCNDEFReaderSession *)session didInvalidateWithError:(NSError *)error

{

NSLog(@"Called: %s", __func__);

NSLog(@"error: %@", error.localizedDescription);

dispatch_async(dispatch_get_main_queue(),^{

});

_ndefSession = nil;

}


iOS 11 Core NFC使用详解_第3张图片
准备扫描



iOS 11 Core NFC使用详解_第4张图片
扫描成功界面


4.参考

测试demo:  https://github.com/bellx2/ios11NFCTest/

常见问题及解决办法: https://stackoverflow.com/questions/44380305/ios-11-core-nfc-any-sample-code

Core NFC文档: https://developer.apple.com/documentation/corenfc


你可能感兴趣的:(iOS 11 Core NFC使用详解)