iOS之框架架构iOS之开发配置iOS 11

iOS11 Core NFC

2017-08-22  本文已影响5159人  EchoZuo

About Core NFC

Core NFC支持的读取数据类型:
image.png
Core NFC框架特性/要求

项目加入Core NFC框架使用的要求

image.png image.png
集成Core NFC中的一些细节说明

示例代码

代码很简单!!!其实Core NFC目前放出的权限很少,只支持特定格式的NFC数据读取,不支持输出和格式设置,所以代码上很简单,可以说是傻瓜式的调用处理即可。我猜想可能是因为Apple为了保证Apple Pay的安全性,毕竟Apple Pay也是采用NFC完成支付。
使用Core NFC
具体代码如下如下
// @import CoreNFC 导入框架
// 遵循 NFCNDEFReaderSessionDelegate 协议
#import "ViewController.h"
#include <sys/types.h>
#include <sys/sysctl.h>

@import CoreNFC;
@interface ViewController ()<NFCNDEFReaderSessionDelegate>
@end
@implementation ViewController

// 创建 NFCNDEFReaderSession 实例,开启NFCNDEFReaderSession
// Tips:开启 
// 条件:iphone7/7plus运行iOS11
if ([ViewController isiPhone7oriPhone7Plus] && [UIDevice currentDevice].systemVersion.floatValue >= 11.0) {
    // ReadingAvailable is YES if device supports NFC tag reading.
    if ([NFCNDEFReaderSession readingAvailable]) {
        // beginScanning
        // invalidateAfterFirstRead 属性表示是否需要识别多个NFC标签,如果是YES,则会话会在第一次识别成功后终止。否则会话会持续
        // 不过有一种例外情况,就是如果响应了-readerSession:didInvalidateWithError:方法,则是否为YES,会话都会被终止
        NFCNDEFReaderSession *session = [[NFCNDEFReaderSession alloc] initWithDelegate:self queue:nil invalidateAfterFirstRead:YES];
        
        [session beginSession];
    }
}

// 处理协议回调方法
#pragma mark - NFCReaderSessionDelegate
// Check invalidation reason from the returned error. A new session instance is required to read new tags.
// 识别出现Error后会话会自动终止,此时就需要程序重新开启会话
- (void)readerSession:(NFCNDEFReaderSession *)session didInvalidateWithError:(NSError *)error {
    // error明细参考NFCError.h
    NSLog(@"%@",error);
}

// Process detected NFCNDEFMessage objects
- (void)readerSession:(NFCNDEFReaderSession *)session didDetectNDEFs:(NSArray<NFCNDEFMessage *> *)messages {
    // 数组messages中是NFCNDEFMessage对象
    // NFCNDEFMessage对象中有一个records数组,这个数组中是NFCNDEFPayload对象
    // 参考NFCNDEFMessage、NFCNDEFPayload类
    // 解析数据
    for (NFCNDEFMessage *message in messages) {
        for (NFCNDEFPayload *playLoad in message.records) {
            NSLog(@"typeNameFormat : %d", playLoad.typeNameFormat);
            NSLog(@"type : %@", playLoad.type);
            NSLog(@"identifier : %@", playLoad.identifier);
            NSLog(@"playload : %@", playLoad.payload);
        }
    }
}

// 主动终止会话,调用如下方法即可。
[session invalidateSession];
运行效果图
image.png image.png
由于身边的NFC卡片都未识别成功,所以图二识别完成后的截图为WWDC视频中的截图。
通过测试,目前用iphone7plus+iOS11测试读取上海交通卡、公司门禁卡,都没有读取成功,代码逻辑应该没有问题。可能是这些NFC芯片数据格式问题?不太确定是什么原因。不过貌似网上有人说是iOS11的问题,可以等iOS11正式版发布后再试试看,我也会持续关注。如果大家有相关的答案也可以告知我。谢谢。

资料

https://github.com/EchoZuo/iOSCoreNFC
https://developer.apple.com/documentation/corenfc#overview
https://developer.apple.com/videos/play/wwdc2017/718/
https://stackoverflow.com/questions/44380305/ios-11-core-nfc-any-sample-code


上一篇 下一篇

猜你喜欢

热点阅读