Turn plug on/off with Homekit SDK in Swift 5

292 Views Asked by At

What is sample code to turn outlet on/off via Homekit SDK in Swift for IOS phone app?

Outlet name is SYLVANIA Outlet-4515, room is Bedroom, home is Holmdel.

1

There are 1 best solutions below

0
On

solved...

var accessories: [HMAccessory] = [] var home: HMHome?

var toggleState: Bool = false var indexPathRow = 0

// For discovering new accessories let browser = HMAccessoryBrowser() var discoveredAccessories: [HMAccessory] = []

@IBAction func onoff(_ sender: Any) {

print ("indexPathRow: ", indexPathRow)

toggleState = toggleState ? false: true
let accessory = accessories[indexPathRow]

guard let characteristic = accessory.find(serviceType: HMServiceTypeOutlet, characteristicType: HMCharacteristicMetadataFormatBool) else {
  return
}


characteristic.writeValue(NSNumber(value: toggleState)) { error in
  if error != nil {
    print("Something went wrong when attempting to update the service characteristic.")
  }
 //
}