2022年3月17日 星期四

用swift讀寫NTag


  1. info.plist中,加入Privacy - NFC Scan Usage Description
  2. Capabilities 加入Near Field Communication Tag Reading
  3. 掃描

    func startScan() {

            let session = NFCNDEFReaderSession(delegate: self, queue: nil, invalidateAfterFirstRead: false)

            session.alertMessage = "Hold your iPhone near an NFC transit card."

            session.begin()

    }

  4. 連線,更新payload

    func readerSession(_ session: NFCNDEFReaderSession, didDetect tags: [NFCNDEFTag]) {

        guard

            let sms = "場所代碼:111111111111111 本次實聯簡訊限防疫目的使用。".addingPercentEncoding(withAllowedCharacters: .urlHostAllowed),

            let payload = NFCNDEFPayload.wellKnownTypeURIPayload(string: "sms:1922&body=\(sms)"),

            let tag = tags.first

        else {

            session.invalidate(errorMessage: "Could not process tag.")

            return

        }

        session.connect(to: tag) { error in

            guard error == nil else {

                session.invalidate(errorMessage: "Could not connect to tag.")

                return

            }

            tag.queryNDEFStatus { status, capacity, error in

                guard error == nil else {

                    session.invalidate(errorMessage: "Could not query status of tag.")

                    return

                }

                

                switch status {

                case .notSupported:

                    session.invalidate(errorMessage: "Tag is not supported.")

                case .readOnly:

                    session.invalidate(errorMessage: "Tag is only readable.")

                case .readWrite:

                    let messge = NFCNDEFMessage.init(records: [payload])

                    tag.writeNDEF(messge) { error in

                        if error != nil {

                            session.invalidate(errorMessage: "Failed to write message.")

                        } else {

                            session.alertMessage = "Successfully configured tag."

                            session.invalidate()

                        }

                    }

                    

                @unknown default:   session.invalidate(errorMessage: "Unknown status of tag.")

                }

            }

        }

    }


PS.找不到 Near Field Communication Tag Reading ,請切換開發者帳號到付費帳號

沒有留言: