我正在尝试使用 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)
}
}
}
Run Code Online (Sandbox Code Playgroud)
为什么我不断收到“错误域=NFCError Code=202“会话意外失效” UserInfo={NSLocalizedDescription=Session 意外失效}”?
我不确定,但在导致此错误的行下方Session is invalidated unexpectedly
当我与 一起工作时CoreNFC,我也遇到过类似的问题。通过定义为来修复它property
let nfcSession = NFCNDEFReaderSession(delegate: self, queue: DispatchQueue(label: "queueName", attributes: .concurrent), invalidateAfterFirstRead: true)
Run Code Online (Sandbox Code Playgroud)
我建议你需要定义nfcSession为财产。
var nfcSession: NFCNDEFReaderSession?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
self.nfcSession = NFCNDEFReaderSession(delegate: self, queue: DispatchQueue.global(qos: .background), invalidateAfterFirstRead: false)
self.nfcSession?.begin()
return true
}
Run Code Online (Sandbox Code Playgroud)
您可以为 iOS 11 定义一个属性,如下所示。
@available(iOS 10.0, *)
var session: NFCNDEFReaderSession?
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2722 次 |
| 最近记录: |