IOS 프로그래밍

본문 바로가기
사이트 내 전체검색


IOS 프로그래밍
IOS 프로그래밍

1. Core NFC 사용하기

페이지 정보

작성자 관리자 댓글 0건 조회 3,483회 작성일 20-01-03 19:13

본문

1. Core NFC 사용하기

Xcode 11, Swift 5 버전을 사용하였다. 



User Interface를 storyboard로 선택하여 프로젝트를 생성한다.



1.png 





7.png



8.png


프로젝트 탐색기에서 ViewController.swift를 선택하여 편집창에 띄우고, 소스코드를 추가한다. 


10.png


 

import UIKit 

import CoreNFC


class ViewController: UIViewController , NFCNDEFReaderSessionDelegate {


    var session: NFCNDEFReaderSession?

    

    override func viewDidLoad() {

        super.viewDidLoad()

        // Do any additional setup after loading the view.

        

        session = NFCNDEFReaderSession(delegate: self, queue: DispatchQueue.main, invalidateAfterFirstRead: false)

        session?.begin()

        

    }

    

    func readerSession(_ session: NFCNDEFReaderSession, didDetectNDEFs messages: [NFCNDEFMessage]) {

        for message in messages {

            for record in message.records {

                if let string = String(data: record.payload, encoding: .ascii) {

                    print(string)

                }

            }

        }

    }


    func readerSession(_ session: NFCNDEFReaderSession, didInvalidateWithError error: Error) {

        print(error.localizedDescription)


    }


}


프로젝트 탐색기에서 NFCReader 프로젝트 명을 선택한다.

가운데 에디터 영역이 속성들로 바뀐다. 

Signing&Capablities 탭을 선택한다. 

NFC-scanning permissions을 추가하기 위해 아래와 같이 한다. 


11.png


[ + Capability ]를 클릭한다. 아래 화면이 뜨면 Near Field Communication Tag Reading 찾아 더블클릭하면 추가된다.


12.png


아래와 같이 추가된 것을 확인할 수 이다. 


13.png


Info 탭에서 아래와 같이 추가한다.


14.png


Privacy - NFC Scan Usage Description을 선택한다. 

value에 NFC tag to scan it을 입력한다.


15.png


아이폰을 연결하여 직접 개발한 어플을 올려 테스트 한다.

USB로 아이폰을 연결하고 아래와 같이 아이폰을 선택한다.


16.png


실행을 클릭한다. Building 과 업로드가 진행된다.


17.png


아이폰에서 실행한 화면이다. 


18.png



과제. 메인 화면에서 버튼을 눌러 NFC 스캔을 실행하도록 수정해보자. 


@IBAction func beginScanning(_ sender: Any) {
    guard NFCNDEFReaderSession.readingAvailable else {
        let alertController = UIAlertController(
            title: "Scanning Not Supported",
            message: "This device doesn't support tag scanning.",
            preferredStyle: .alert
        )
        alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
        self.present(alertController, animated: true, completion: nil)
        return
    }

    session = NFCNDEFReaderSession(delegate: self, queue: nil, invalidateAfterFirstRead: false)
    session?.alertMessage = "Hold your iPhone near the item to learn more about it."
    session?.begin()
}


func readerSession(_ session: NFCNDEFReaderSession, didDetectNDEFs messages: [NFCNDEFMessage]) {
    DispatchQueue.main.async {
        // Process detected NFCNDEFMessage objects.
        
    }
}


func readerSession(_ session: NFCNDEFReaderSession, didInvalidateWithError error: Error) {
    // Check the invalidation reason from the returned error.
    if let readerError = error as? NFCReaderError {
        // Show an alert when the invalidation reason is not because of a
        // successful read during a single-tag read session, or because the
        // user canceled a multiple-tag read session from the UI or
        // programmatically using the invalidate method call.
        if (readerError.code != .readerSessionInvalidationErrorFirstNDEFTagRead)
            && (readerError.code != .readerSessionInvalidationErrorUserCanceled) {
            let alertController = UIAlertController(
                title: "Session Invalidated",
                message: error.localizedDescription,
                preferredStyle: .alert
            )
            alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
            DispatchQueue.main.async {
                self.present(alertController, animated: true, completion: nil)
            }
        }
    }

    // To read new tags, a new session instance is required.
    self.session = nil
}

댓글목록

등록된 댓글이 없습니다.


개인정보취급방침 서비스이용약관 모바일 버전으로 보기 상단으로

TEL. 063-469-4551 FAX. 063-469-4560 전북 군산시 대학로 558
군산대학교 컴퓨터정보공학과

Copyright © www.leelab.co.kr. All rights reserved.