当应用程序完成 NFC 扫描时,如何更新视图?

How can I update the view when the app is done scanning for NFC?

我有一个从 NFC 卡读取的 Swift 应用程序。我希望它在屏幕上显示它读取的数据,如果我有一个使用 getDetected() 函数检查更新数据的按钮,我就可以做到这一点。但是,我想在完成读取 NFC 标签后更新视图,以便我可以立即显示数据。我该怎么做?

NFC Reader class:

import Foundation
import CoreNFC

class NFCReader: NSObject, NFCNDEFReaderSessionDelegate {
    var detected = [NFCNDEFMessage]()
    var session: NFCNDEFReaderSession?
    func beginScanning() {
        guard NFCNDEFReaderSession.readingAvailable else { return }
        session = NFCNDEFReaderSession(delegate: self, queue: nil, invalidateAfterFirstRead: true)
        session?.alertMessage = "Hold your iPhone near the reader to unlock."
        session?.begin()
    }
    func readerSession(_ session: NFCNDEFReaderSession, didDetectNDEFs messages: [NFCNDEFMessage]) {
        self.detected = messages
        self.session = nil
    }
    func readerSession(_ session: NFCNDEFReaderSession, didInvalidateWithError error: Error) {
        self.session = nil
    }
    func getDetected() -> [NFCNDEFMessage] {
        return detected
    }
}

您可以尝试以下方法,使用 ObservableObject。 每当 @Published var detected 更改时,UI 将更新。

class NFCReader: NSObject, NFCNDEFReaderSessionDelegate, ObservableObject { // <--- here
    @Published var detected = [NFCNDEFMessage]()  // <--- here
    
    var session: NFCNDEFReaderSession?
    
    func beginScanning() {
        guard NFCNDEFReaderSession.readingAvailable else { return }
        session = NFCNDEFReaderSession(delegate: self, queue: nil, invalidateAfterFirstRead: true)
        session?.alertMessage = "Hold your iPhone near the reader to unlock."
        session?.begin()
    }
    
    func readerSession(_ session: NFCNDEFReaderSession, didDetectNDEFs messages: [NFCNDEFMessage]) {
        self.detected = messages
        self.session = nil
    }
    
    func readerSession(_ session: NFCNDEFReaderSession, didInvalidateWithError error: Error) {
        self.session = nil
    }
    
    // no real need for this
    func getDetected() -> [NFCNDEFMessage] {
        return detected
    }
    
}


struct ContentView: View {
    @StateObject var readerNFC = NFCReader()  // <-- here
    
    var body: some View {
        ForEach(readerNFC.detected, id: \.self) { msg in
           //     .....
        }
    }
    
}