قالب وردپرس درنا توس
Home / IOS Development / # 298: Switching light colors with HomeKit 💡🌈 – Small pieces of cocoa

# 298: Switching light colors with HomeKit 💡🌈 – Small pieces of cocoa



Subjects

Topics

In Bite # 297, we learned how to simulate a light bulb accessory using Apple's HomeKit Accessory Simulator. Today we continue where we left and learn to change the color of our light bulb.

Let's go diving.

Everything in HomeKit is built around HMHomeManager type. We use this manager to communicate with homes, accessories and more:

  la    manager    =    HMHomeManager   () 
  manager    delegate [1
9659015]


We have set us as delegate here so that we can implement a function :

  extension   ] ViewController   :    HMHomeManagerDelegate   {
    FUNC    homeManagerDidUpdateHomes   (  _    leather :    HMHomeManager )   {
      // TODO 
  } 
} 

As with all user data, we must request permission before we access the user's HomeKit data. Once the user has allowed us, the feature homeManagerDidUpdateHomes will be called. This feature will also be called whenever significant changes occur in a home .

We can use this as a queue to update the app's user interface to match. Nice.

Okay, let's have fun and see what it would look like (in code) to swap all the lights in the house to another color. [19659000] First, let's get all the lights ] :

  func    homeManagerDidUpdateHomes   (  _    manager :    HMHomeManager )   {
    guard    With    home    =    manager .   home .   first    other   {   return  } [19659062] la    lights    =    home .   accessories .   filter   {   $ 0 .   in the category .   categoryType    ==    HMAccessoryCategoryTypeLightbulb  } 
} 

Fine. We now have an array of all lights in our home as HMAccessory objects. In order to make changes, we must come to the services and properties in of each accessory


Source link