iOS NFC读取tag功能实现

首先引用框架

#import 

遵守协议

设置属性

@property(strong,nonatomic)NFCTagReaderSession *session;

@property(strong,nonatomic)id currentTag;

做好机型以及系统版本判断

if (@available(iOS 13.0, *)) {
            if (NFCNDEFReaderSession.readingAvailable) {
                self.session = [[NFCTagReaderSession alloc]
                                    initWithPollingOption:(NFCPollingISO14443 | NFCPollingISO15693 | NFCPollingISO15693) delegate:self queue:dispatch_get_main_queue()];
                self.session.alertMessage = @"读取卡片,请将卡片靠近手机";
                [self.session beginSession]; //开始识别 弹出识别提示框
            }else{
                [SVProgressHUD showInfoWithStatus:@"NFC功能只支持iphone7以及iOS13.0以上设备"];
            }
        }else{
            [SVProgressHUD showInfoWithStatus:@"NFC功能只支持iphone7以及iOS13.0以上设备"];
        }

实现代理方法以及转化data数据

- (void)tagReaderSession:(NFCTagReaderSession *)session didDetectTags:(NSArray<__kindof id> *)tags API_AVAILABLE(ios(13.0)) API_UNAVAILABLE(watchos, macos, tvos){
    _currentTag = [tags firstObject];
    NSData *data ;
    if (self.currentTag.type == NFCTagTypeMiFare) {
        id mifareTag = [self.currentTag asNFCMiFareTag];
        data = mifareTag.identifier;
    }else if (self.currentTag.type == NFCTagTypeISO15693){
        id mifareTag = [self.currentTag asNFCISO15693Tag];
        data = mifareTag.identifier;
    }else if (self.currentTag.type == NFCTagTypeISO15693){
        id mifareTag = [self.currentTag asNFCISO15693Tag];
        data = mifareTag.identifier;
    }else{
        [SVProgressHUD showErrorWithStatus:@"未识别出NFC格式"];
    }
    
    NSString *str = [self convertDataBytesToHex:data];
    
    //识别成功处理
    
    [session invalidateSession];
    
}



- (NSString *)convertDataBytesToHex:(NSData *)dataBytes {
    if (!dataBytes || [dataBytes length] == 0) {
        return @"";
    }
    NSMutableString *hexStr = [[NSMutableString alloc] initWithCapacity:[dataBytes length]];
    [dataBytes enumerateByteRangesUsingBlock:^(const void *bytes, NSRange byteRange, BOOL *stop) {
        unsigned char *dataBytes = (unsigned char *)bytes;
        for (NSInteger i = 0; i < byteRange.length; i ++) {
            NSString *singleHexStr = [NSString stringWithFormat:@"%x", (dataBytes[i]) & 0xff];
            if ([singleHexStr length] == 2) {
                [hexStr appendString:singleHexStr];
            } else {
                [hexStr appendFormat:@"0%@", singleHexStr];
            }
        }
    }];
    return hexStr;
}

- (void)tagReaderSession:(NFCTagReaderSession *)session didInvalidateWithError:(NSError *)error{
    if (error.code == 200) {
        return;
    }
    [SVProgressHUD showErrorWithStatus:error.localizedDescription];
    [session invalidateSession];
}

参考链接:https://blog.csdn.net/Han_SM/article/details/103046741

你可能感兴趣的:(备忘)