【发布时间】:2020-01-12 22:41:58
【问题描述】:
我正在尝试使用 NFC。我遵循了这些步骤:
在此之后,我导入了 CoreNFC 并实现了这些代码:
@available(iOS 11.0, *)
extension EventPreviewViewController: NFCNDEFReaderSessionDelegate {
func readerSession(_ session: NFCNDEFReaderSession, didInvalidateWithError error: Error) {
let alert = UIAlertController.withOkButton(andTitle: NSLocalizedString("TitleWarning"), andText: NSLocalizedString("ErrorNFCInvalidate"), okHandler: nil)
self.present(alert, animated: true, completion: nil)
}
func readerSession(_ session: NFCNDEFReaderSession, didDetectNDEFs messages: [NFCNDEFMessage]) {
// TODO
}
}
class EventPreviewViewController: UITableViewController {
@available(iOS 11.0, *)
var nfcSession: NFCNDEFReaderSession {
return NFCNDEFReaderSession(delegate: self, queue: nil, invalidateAfterFirstRead: true)
}
@IBAction func startAccess(_ sender: UIButton) {
if #available(iOS 11.0, *) {
nfcSession.begin()
} else {
let alert = UIAlertController.withOkButton(andTitle: NSLocalizedString("TitleWarning"), andText: NSLocalizedString("ErrorNFCUnsupported"), okHandler: nil)
self.present(alert, animated: true, completion: nil)
}
}
}
为什么我不断收到“Error Domain=NFCError Code=202 "Session is invalidated unexpectedly" UserInfo={NSLocalizedDescription=Session is invalidated unexpectedly}”?
【问题讨论】:
-
您是否断章取意地声明了
nfcSession?我想是这样,因为显示的代码不会编译。您需要nfcSession成为属性,而不是局部常量,否则它将在其封闭函数返回后立即释放。 -
我尝试将
nfcSession设为属性(请参阅下面答案中的评论)但仍然无法正常工作... -
请edit 您的问题在上下文中显示相关的属性声明 - 您将它设为哪个对象的属性?该对象的生命周期是多少?消息说您的阅读器会话正在释放。