NFCDetectVC.swift 9.5 KB
//
//  NFCDetectVC.swift
//  Twear
//
//  Created by yangbin on 2022/2/12.
//

import UIKit
import CoreNFC
import RealmSwift

class NFCDetectVC: UIViewController, NFCNDEFReaderSessionDelegate {
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
   
        if #available(iOS 11.0, *) {
            let session = NFCNDEFReaderSession(delegate: self, queue: nil, invalidateAfterFirstRead: true)
            session.alertMessage = LocString("准备读取,请将卡片贴近手机")
            session.begin()
       
        } else {
            // Fallback on earlier versions
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        title = LocString("检测门禁卡")
        
    }
    
    
    
    @available(iOS 11.0, *)
    func readerSession(_ session: NFCNDEFReaderSession, didInvalidateWithError error: Error) {
        
    }
    
    @available(iOS 11.0, *)
    func readerSession(_ session: NFCNDEFReaderSession, didDetectNDEFs messages: [NFCNDEFMessage]) {
        
        for message in messages {
            if let record = message.records.first {
                DispatchQueue.main.async {
                    session.alertMessage = LocString("读取成功")
                    let nfc = NFCModel()
                    nfc.identifier = String(data: record.identifier, encoding: .utf8) ?? ""
                    nfc.payload = String(data: record.payload, encoding: .utf8) ?? ""
                    nfc.type = String(data: record.type, encoding: .utf8) ?? ""
                    switch record.typeNameFormat {
                    case .empty:
                        nfc.format = "empty"
                    case .nfcWellKnown:
                        nfc.format = "nfcWellKnown"
                    case .media:
                        nfc.format = "media"
                    case .absoluteURI:
                        nfc.format = "absoluteURI"
                    case .nfcExternal:
                        nfc.format = "nfcExternal"
                    case .unknown:
                        nfc.format = "unknown"
                    case .unchanged:
                        nfc.format = "unchanged"
                    default:
                        nfc.format = "unknown"
                    }
                    let user = UserInfo
                    user.nfc.append(nfc)
                    AdminHelper.shared.updateUser(user)
                    //                    if device.nfc.count == 1 {
                    if #available(iOS 13.0, *) {
                        let vc = UIStoryboard.loadViewControllerIdentifier(storyboardName: "Setting", identifier: "NFCViewController") as! NFCViewController
                        
                        // Fallback on earlier versions
                        
                        vc.nfcList = user.nfc
                        self.navigationController?.pushViewController(vc, animated: true)
                        //                    } else {
                        //                        if (self.navigationController?.viewControllers.count)! >= 2 {
                        //                            guard let vc = self.navigationController?.viewControllers[1] else { return
                        //                            }
                        //                            self.navigationController?.popToViewController(vc, animated: true)
                        //                        }
                        //                    }
                        
                    }
                    print(nfc.identifier)
                    print(nfc.payload)
                    print(nfc.type)
                    print(nfc.format)
                }
            }
        }
    }
    
    /// - Tag: processingNDEFTag
    @available(iOS 13.0, *)
    func readerSession(_ session: NFCNDEFReaderSession, didDetect tags: [NFCNDEFTag]) {
        if tags.count > 1 {
            // Restart polling in 500ms
            let retryInterval = DispatchTimeInterval.milliseconds(500)
            session.alertMessage = LocString("读取失败")//"More than 1 tag is detected, please remove all tags and try again."
            DispatchQueue.global().asyncAfter(deadline: .now() + retryInterval, execute: {
                session.restartPolling()
            })
            return
        }
        
        // Connect to the found tag and perform NDEF message reading
        let tag = tags.first!
        session.connect(to: tag, completionHandler: { (error: Error?) in
            if nil != error {
                session.alertMessage = LocString("读取失败")//"Unable to connect to tag."
                session.invalidate()
                return
            }
            
            tag.queryNDEFStatus(completionHandler: { (ndefStatus: NFCNDEFStatus, capacity: Int, error: Error?) in
                if .notSupported == ndefStatus {
                    session.alertMessage = LocString("读取失败")//"Tag is not NDEF compliant"
                    session.invalidate()
                    return
                } else if nil != error {
                    session.alertMessage = LocString("读取失败")//"Unable to query NDEF status of tag"
                    session.invalidate()
                    return
                }
                
                tag.readNDEF(completionHandler: { (message: NFCNDEFMessage?, error: Error?) in
                    var statusMessage: String
                    if nil != error || nil == message {
                        statusMessage = LocString("读取失败")
                    } else {
                        statusMessage = LocString("读取成功")
                        DispatchQueue.main.async {
                            if let record = message?.records.first {
                                //                            session.alertMessage =
                                let nfc = NFCModel()
                                nfc.identifier = String(data: record.identifier, encoding: .utf8) ?? ""
                                nfc.payload = String(data: record.payload, encoding: .utf8) ?? ""
                                nfc.type = String(data: record.type, encoding: .utf8) ?? ""
                                switch record.typeNameFormat {
                                case .empty:
                                    nfc.format = "empty"
                                case .nfcWellKnown:
                                    nfc.format = "nfcWellKnown"
                                case .media:
                                    nfc.format = "media"
                                case .absoluteURI:
                                    nfc.format = "absoluteURI"
                                case .nfcExternal:
                                    nfc.format = "nfcExternal"
                                case .unknown:
                                    nfc.format = "unknown"
                                case .unchanged:
                                    nfc.format = "unchanged"
                                default:
                                    nfc.format = "unknown"
                                }
                                let user = UserInfo
                                user.nfc.append(nfc)
                                AdminHelper.shared.updateUser(user)
                                //                    if device.nfc.count == 1 {
                                
                                let vc = UIStoryboard.loadViewControllerIdentifier(storyboardName: "Setting", identifier: "NFCViewController") as! NFCViewController
                                
                                // Fallback on earlier versions
                                
                                vc.nfcList = user.nfc
                                self.navigationController?.pushViewController(vc, animated: true)
                                //                    } else {
                                //                        if (self.navigationController?.viewControllers.count)! >= 2 {
                                //                            guard let vc = self.navigationController?.viewControllers[1] else { return
                                //                            }
                                //                            self.navigationController?.popToViewController(vc, animated: true)
                                //                        }
                                //                    }
                                
                            }
                            // Process detected NFCNDEFMessage objects.
                            //                            self.detectedMessages.append(message!)
                            //                            self.tableView.reloadData()
                        }
                    }
                    
                    session.alertMessage = statusMessage
                    session.invalidate()
                })
            })
        })
    }
    
    @IBAction func problem(_ sender: Any) {
        let vc = UIStoryboard.loadViewControllerIdentifier(storyboardName: "Setting", identifier: "NFCProblemsVC")
        navigationController?.pushViewController(vc, animated: true)
    }
    
    /*
     // MARK: - Navigation
     
     // In a storyboard-based application, you will often want to do a little preparation before navigation
     override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
     // Get the new view controller using segue.destination.
     // Pass the selected object to the new view controller.
     }
     */
    
}