欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

iOS NFC

程序员文章站 2022-05-27 22:33:07
#import @interface ViewController () @property (nonatomic,retain) UIButton *beginTestBtn; @property (nonatomic,retain) UILabel *textLabel; @end @imple... ......

 

 

#import <corenfc/corenfc.h>


@interface viewcontroller ()<nfcndefreadersessiondelegate>

@property (nonatomic,retain) uibutton *begintestbtn;

@property (nonatomic,retain) uilabel *textlabel;


@end

@implementation viewcontroller

- (void)viewdidload {
    [super viewdidload];
    
    _begintestbtn = [[uibutton alloc]initwithframe:cgrectmake(100, 100, 100, 50)];
    [_begintestbtn settitle:@"开始读取" forstate:uicontrolstatenormal];
    [_begintestbtn settitlecolor:[uicolor bluecolor] forstate:uicontrolstatenormal];
    _begintestbtn.titlelabel.textalignment = nstextalignmentleft;
    [_begintestbtn addtarget:self action:@selector(begintestbtnaction) forcontrolevents:uicontroleventtouchupinside];
    
    
    _textlabel = [[uilabel alloc]initwithframe:cgrectmake(120, 180, 200, 50)];
    _textlabel.text = @"待读取";
    _textlabel.textcolor = [uicolor orangecolor];
    [self.view addsubview:_textlabel];
    
    nslog(@"进入vc");
    
    [self.view addsubview:_begintestbtn];
    [self.view addsubview:_textlabel];
    
    
    // do any additional setup after loading the view, typically from a nib.
}


-(void)begintestbtnaction
{
    
    /**
     三个参数
     第一个参数:代理对象
     第二个参数:线程
     第三个参数:session读取一个还是多个ndef。yes:读取一个结束,no:读取多个
     */
    
    nfcndefreadersession *session = [[nfcndefreadersession alloc] initwithdelegate:self queue:dispatch_queue_create(null, dispatch_queue_concurrent) invalidateafterfirstread:yes];
    
    [session beginsession];
    
}


/**
 代理
 */
- (void) readersession:(nonnull nfcndefreadersession *)session diddetectndefs:(nonnull nsarray<nfcndefmessage *> *)messages {
    
    __weak typeof(self) weakself=self;
    dispatch_async(dispatch_get_main_queue(), ^{
        weakself.textlabel.text = @"读取成功";
    });
    
    for (nfcndefmessage *message in messages) {
        for (nfcndefpayload *payload in message.records) {
            nslog(@"payload data:%@",payload.payload);
        }
    }
}

- (void)readersession:(nfcndefreadersession *)session didinvalidatewitherror:(nserror *)error{
    
     nslog(@"error:%@",error);
    
    __weak typeof(self) weakself=self;
    dispatch_async(dispatch_get_main_queue(), ^{
        weakself.textlabel.text = @"读取失败";
    });
    
    
}