#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 = @"讀取失敗"; }); }