HomeKit - How to update accessory isReachable value, when i come back from background to foreground?

603 Views Asked by At

Situation: i am developing an app, which manages HomeKit accessories. For example i do that:

  1. Accessory is power on, and i see it via app. Also in foreground mode HMAccessoryDelegate method:

func accessoryDidUpdateReachability(HMAccessory)

works fine and i can handle status of my accessory.

  1. I switch app to background mode.

  2. I turn off accessory (i mean completely power off) so it must be unreachable.

  3. I switch app to foreground mode, but accessory is still reachable. method func accessoryDidUpdateReachability(HMAccessory) — not called. value accessory.isReachable not updated.

Example of code when i go to foreground:

func applicationDidBecomeActive(_ application: UIApplication) {  
    if let home = HomeStore.sharedStore.home {  
        for accessory in home.accessories {  
            print(accessory.isReachable) //not updated  
            for service in accessory.services {  
                for characteristic in service.characteristics {  
                    characteristic.readValue { (error) in //updated  
                        if error == nil {  
                            let notification = Notification(name: Notification.Name(rawValue: "UpdatedCharacteristic"))  
                            NotificationCenter.default.post(notification)  
                        }  
                    }  
                }  
            }  
        }  
    }  
}

Question: how to update isReachable values of accessories, when i come back from background mode to foreground?

1

There are 1 best solutions below

0
On

You can create a function in the ViewController that implements HMHomeManagerDelegate:

func startHomeManager() {
    manager = HMHomeManager()
    manager.delegate = self

    // do something here
}

and add a call to startHomeManager() to your viewDidLoad(). That will refresh your HMHome object. Then call this func in your AppDelegate:

func applicationWillEnterForeground(_ application: UIApplication) {
    viewController.startHomeManager()
    viewController.didRestartHomeManager()
}

A bonus is that you can call startHomeManager() for pull to refresh, etc.