I'm developing a ticket app with Host card emulation. The session starts correctly the first time, but when trying to emulate a second ticket, after the first one has been read by the reader, or after the emulation has been canceled by the user, it doesn't work correctly for a while.
This is my CardSessionManager:
import CoreNFC
@available(iOS 17.4, *) class CardSessionManager { private static var cardSession: CardSession? = nil private static var presentmentIntent: NFCPresentmentIntentAssertion? = nil
static func initCardSession(_ accessCode: String) { cardSession?.invalidate() cardSession = nil let ProcessAPDU: (_: Data) -> Data = { capdu in var response = Data(accessCode.utf8) response.append(0x90) response.append(0x00) return response } Task { guard NFCReaderSession.readingAvailable, CardSession.isSupported, await CardSession.isEligible else { return } do { presentmentIntent = try await NFCPresentmentIntentAssertion.acquire() cardSession = try await CardSession() } catch { return } if let cardSession { for try await event in cardSession.eventStream { switch event { case .sessionStarted: cardSession.alertMessage = String(localized: "Searching reader...") try await cardSession.startEmulation() case .readerDetected: cardSession.alertMessage = String(localized: "Reading...") case .readerDeselected: cardSession.alertMessage = String(localized: "Successful reading!") await cardSession.stopEmulation(status: .success) case .received(let cardAPDU): cardSession.alertMessage = String(localized: "Communicating with reader.") do { try await cardAPDU.respond(response: ProcessAPDU(cardAPDU.payload)) } catch { cardSession.alertMessage = error.localizedDescription } case .sessionInvalidated(reason: _): cardSession.alertMessage = String(localized: "Ending communication with reader.") presentmentIntent = nil @unknown default: break } } } } }
}