简体   繁体   中英

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

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM