@@ -167,42 +167,46 @@ public final class LockEventsViewController: TableViewController {
167167 let locks = self . locks
168168 let context = Store . shared. backgroundContext
169169
170- if Store . shared. lockManager. central. state == . poweredOn {
171- performActivity ( queue: . bluetooth, { [ weak self] in
172- for lock in locks {
173- guard let device = try Store . shared. device ( for: lock, scanDuration: 1.0 ) else {
174- if self ? . lock == nil {
175- continue
176- } else {
177- throw CentralError . unknownPeripheral
178- }
179- }
180- let lastEventDate = try context. performErrorBlockAndWait {
181- try context. find ( identifier: lock, type: LockManagedObject . self)
182- . flatMap { try $0. lastEvent ( in: context) ? . date }
183- }
184- let fetchRequest = FetchRequest (
185- offset: 0 ,
186- limit: nil ,
187- predicate: Predicate (
188- keys: nil ,
189- start: lastEventDate,
190- end: nil
191- )
170+ performActivity ( queue: . app, { [ weak self] in
171+ guard let self = self else { return }
172+ let expectsLock = self . lock != nil
173+ for lock in locks {
174+
175+ // fetch request
176+ let lastEventDate = try context. performErrorBlockAndWait {
177+ try context. find ( identifier: lock, type: LockManagedObject . self)
178+ . flatMap { try $0. lastEvent ( in: context) ? . date }
179+ }
180+ let fetchRequest = FetchRequest (
181+ offset: 0 ,
182+ limit: nil ,
183+ predicate: Predicate (
184+ keys: nil ,
185+ start: lastEventDate,
186+ end: nil
192187 )
193- do { try Store . shared. listEvents ( device, fetchRequest: fetchRequest) }
194- catch {
195- if self ? . lock == nil {
196- continue
197- } else {
198- throw error
199- }
188+ )
189+ // first try via Bonjour
190+ if let netService = try Store . shared. netServiceClient. discover ( duration: 1.0 , timeout: 10.0 ) . first ( where: { $0. identifier == lock } ) {
191+
192+ try Store . shared. listEvents ( netService, fetchRequest: fetchRequest)
193+
194+ } else if Store . shared. lockManager. central. state == . poweredOn,
195+ let device = try DispatchQueue . bluetooth. sync ( execute: { try Store . shared. device ( for: lock, scanDuration: 2.0 ) } ) {
196+
197+ try DispatchQueue . bluetooth. sync {
198+ _ = try Store . shared. listEvents ( device, fetchRequest: fetchRequest)
200199 }
200+
201+ } else if expectsLock {
202+ throw LockError . notInRange ( lock: lock)
203+ } else {
204+ continue
201205 }
202- } , completion : { ( viewController , _ ) in
203- viewController . needsKeys . removeAll ( )
204- } )
205- }
206+ }
207+ } , completion : { ( viewController , _ ) in
208+ viewController . needsKeys . removeAll ( )
209+ } )
206210 }
207211
208212 private subscript ( indexPath: IndexPath ) -> EventManagedObject {
0 commit comments