我无法在 SwiftUI 中实现 NFCNDEFReaderSessionDelegate
所以我创建了一个类来实现它
struct ContentView: View {
@State var out="n/a"
var body: some View {
VStack{
Text(out)
Button(
action:{
self.scan()
},
label:{Text("Scan")}
)
}
}
func scan(){
var nfc=Nfc()
nfc.start()
out = ???
}
}
NFC.swift
class Nfc: NSObject, NFCNDEFReaderSessionDelegate{
func start(){
let session = NFCNDEFReaderSession(delegate: self, queue: nil, invalidateAfterFirstRead: true)
session.begin()
print("start")
}
func readerSession(_ session: NFCNDEFReaderSession, didInvalidateWithError error: Error) {
print("didInvalidateWithError")
}
func readerSession(_ session: NFCNDEFReaderSession, didDetectNDEFs messages: [NFCNDEFMessage]) {
print("scan")
}
func readerSessionDidBecomeActive(_ session: NFCNDEFReaderSession) {
print("readerSessionDidBecomeActive")
}
}
我可以成功扫描 NFC 标签,但它没有触发任何回调,只显示这个错误
[CoreNFC] 00000002 81bfda80 -[NFCNDEFReaderSession _callbackDidBecomeActive]:228 Delegate does not implement -readerSessionDidBecomeActive: method
但我实际上实现了这个方法。
如果我添加此方法,我将无法扫描标签。
func readerSession(_ session: NFCNDEFReaderSession, didDetect tags: [NFCNDEFTag]) {
print("didDetect")
}