Blame view

HDFwear/Setting/NFC/NFCDetectVC.swift 9.9 KB
f2cf74c7   yangbin   1.0.20(4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
  //
  //  NFCDetectVC.swift
  //  Twear
  //
  //  Created by yangbin on 2022/2/12.
  //
  
  import UIKit
  import CoreNFC
  import RealmSwift
  
  class NFCDetectVC: UIViewController, NFCNDEFReaderSessionDelegate {
      
      @IBOutlet weak var retryBtn: UIButton!
      
      
      override func viewDidAppear(_ animated: Bool) {
          super.viewDidAppear(animated)
     
          if #available(iOS 11.0, *) {
              let session = NFCNDEFReaderSession(delegate: self, queue: nil, invalidateAfterFirstRead: true)
              session.alertMessage = LocString("准备读取,请将卡片贴近手机")
              session.begin()
         
          } else {
              // Fallback on earlier versions
          }
      }
      
      override func viewDidLoad() {
          super.viewDidLoad()
          title = LocString("检测门禁卡")
  //        retryBtn.isHidden = true
          
      }
      
      
      @IBAction func retry(_ sender: Any) {
          if #available(iOS 11.0, *) {
              let session = NFCNDEFReaderSession(delegate: self, queue: nil, invalidateAfterFirstRead: true)
              session.alertMessage = LocString("准备读取,请将卡片贴近手机")
              session.begin()
          }
      }
      
      @available(iOS 11.0, *)
      func readerSession(_ session: NFCNDEFReaderSession, didInvalidateWithError error: Error) {
          
      }
      
      @available(iOS 11.0, *)
      func readerSession(_ session: NFCNDEFReaderSession, didDetectNDEFs messages: [NFCNDEFMessage]) {
          
          for message in messages {
              if let record = message.records.first {
                  DispatchQueue.main.async {
                      session.alertMessage = LocString("读取成功")
                      let nfc = NFCModel()
                      nfc.identifier = String(data: record.identifier, encoding: .utf8) ?? ""
                      nfc.payload = String(data: record.payload, encoding: .utf8) ?? ""
                      nfc.type = String(data: record.type, encoding: .utf8) ?? ""
                      switch record.typeNameFormat {
                      case .empty:
                          nfc.format = "empty"
                      case .nfcWellKnown:
                          nfc.format = "nfcWellKnown"
                      case .media:
                          nfc.format = "media"
                      case .absoluteURI:
                          nfc.format = "absoluteURI"
                      case .nfcExternal:
                          nfc.format = "nfcExternal"
                      case .unknown:
                          nfc.format = "unknown"
                      case .unchanged:
                          nfc.format = "unchanged"
                      default:
                          nfc.format = "unknown"
                      }
                      let user = UserInfo
                      user.nfc.append(nfc)
                      AdminHelper.shared.updateUser(user)
                      //                    if device.nfc.count == 1 {
                      if #available(iOS 13.0, *) {
                          let vc = UIStoryboard.loadViewControllerIdentifier(storyboardName: "Setting", identifier: "NFCViewController") as! NFCViewController
                          
                          // Fallback on earlier versions
                          
                          vc.nfcList = user.nfc
                          self.navigationController?.pushViewController(vc, animated: true)
                          //                    } else {
                          //                        if (self.navigationController?.viewControllers.count)! >= 2 {
                          //                            guard let vc = self.navigationController?.viewControllers[1] else { return
                          //                            }
                          //                            self.navigationController?.popToViewController(vc, animated: true)
                          //                        }
                          //                    }
                          
                      }
                      print(nfc.identifier)
                      print(nfc.payload)
                      print(nfc.type)
                      print(nfc.format)
                  }
              }
          }
      }
      
      /// - Tag: processingNDEFTag
      @available(iOS 13.0, *)
      func readerSession(_ session: NFCNDEFReaderSession, didDetect tags: [NFCNDEFTag]) {
          if tags.count > 1 {
              // Restart polling in 500ms
              let retryInterval = DispatchTimeInterval.milliseconds(500)
              session.alertMessage = LocString("读取失败")//"More than 1 tag is detected, please remove all tags and try again."
              DispatchQueue.global().asyncAfter(deadline: .now() + retryInterval, execute: {
                  session.restartPolling()
              })
              return
          }
          
          // Connect to the found tag and perform NDEF message reading
          let tag = tags.first!
          session.connect(to: tag, completionHandler: { (error: Error?) in
              if nil != error {
                  session.alertMessage = LocString("读取失败")//"Unable to connect to tag."
                  session.invalidate()
                  return
              }
              
              tag.queryNDEFStatus(completionHandler: { (ndefStatus: NFCNDEFStatus, capacity: Int, error: Error?) in
                  if .notSupported == ndefStatus {
                      session.alertMessage = LocString("读取失败")//"Tag is not NDEF compliant"
                      session.invalidate()
                      return
                  } else if nil != error {
                      session.alertMessage = LocString("读取失败")//"Unable to query NDEF status of tag"
                      session.invalidate()
                      return
                  }
                  
                  tag.readNDEF(completionHandler: { (message: NFCNDEFMessage?, error: Error?) in
                      var statusMessage: String
                      if nil != error || nil == message {
                          statusMessage = LocString("读取失败")
                      } else {
                          statusMessage = LocString("读取成功")
                          DispatchQueue.main.async {
                              if let record = message?.records.first {
                                  //                            session.alertMessage =
                                  let nfc = NFCModel()
                                  nfc.identifier = String(data: record.identifier, encoding: .utf8) ?? ""
                                  nfc.payload = String(data: record.payload, encoding: .utf8) ?? ""
                                  nfc.type = String(data: record.type, encoding: .utf8) ?? ""
                                  switch record.typeNameFormat {
                                  case .empty:
                                      nfc.format = "empty"
                                  case .nfcWellKnown:
                                      nfc.format = "nfcWellKnown"
                                  case .media:
                                      nfc.format = "media"
                                  case .absoluteURI:
                                      nfc.format = "absoluteURI"
                                  case .nfcExternal:
                                      nfc.format = "nfcExternal"
                                  case .unknown:
                                      nfc.format = "unknown"
                                  case .unchanged:
                                      nfc.format = "unchanged"
                                  default:
                                      nfc.format = "unknown"
                                  }
                                  let user = UserInfo
                                  user.nfc.append(nfc)
                                  AdminHelper.shared.updateUser(user)
                                  //                    if device.nfc.count == 1 {
                                  
                                  let vc = UIStoryboard.loadViewControllerIdentifier(storyboardName: "Setting", identifier: "NFCViewController") as! NFCViewController
                                  
                                  // Fallback on earlier versions
                                  
                                  vc.nfcList = user.nfc
                                  self.navigationController?.pushViewController(vc, animated: true)
                                  //                    } else {
                                  //                        if (self.navigationController?.viewControllers.count)! >= 2 {
                                  //                            guard let vc = self.navigationController?.viewControllers[1] else { return
                                  //                            }
                                  //                            self.navigationController?.popToViewController(vc, animated: true)
                                  //                        }
                                  //                    }
                                  
                              }
                              // Process detected NFCNDEFMessage objects.
                              //                            self.detectedMessages.append(message!)
                              //                            self.tableView.reloadData()
                          }
                      }
                      
                      session.alertMessage = statusMessage
                      session.invalidate()
                  })
              })
          })
      }
      
      @IBAction func problem(_ sender: Any) {
          let vc = UIStoryboard.loadViewControllerIdentifier(storyboardName: "Setting", identifier: "NFCProblemsVC")
          navigationController?.pushViewController(vc, animated: true)
      }
      
      /*
       // MARK: - Navigation
       
       // In a storyboard-based application, you will often want to do a little preparation before navigation
       override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
       // Get the new view controller using segue.destination.
       // Pass the selected object to the new view controller.
       }
       */
      
  }