iOS 11 有許多新的 API 包含 CoreML , ARKit , CoreNFC 等
今天要來實作CoreNFC
Support Devices
實作方式
設置 Certificates, Identifiers & Profiles (Entitlements)
Xcode->Capabilities->Near Field Communication Tag Reading
設置 Info.plist
在 Info.Plist 添加 Privacy - NFC Scan Usage Description
實作 NFCNDEFReaderSessionDelegate
override func viewDidLoad() {
super.viewDidLoad()
let session = NFCNDEFReaderSession.init(delegate: self, queue: nil, invalidateAfterFirstRead: true)
session.begin()
// Do any additional setup after loading the view.
}
實作 NFCNDEFReaderSession 的 兩個 Delegate
//當有錯誤時會呼叫這個Delegate
func readerSession(_ session: NFCNDEFReaderSession, didInvalidateWithError error: Error) {
}
//當有讀到tag會呼叫這個Delegate
func readerSession(_ session: NFCNDEFReaderSession, didDetectNDEFs messages: [NFCNDEFMessage]) {
//解析tag資訊
messages.forEach { (message) in
message.records.forEach({ (item) in
print(item.payload)
print(item.identifier)
print(item.type)
print(item.typeNameFormat)
})
}
}
這篇文章說來心酸發了兩次才成功