swiftdelegateshomekitios-homekit

HMHomeManager returning nil


I'm creating my own "HouseKit" based on HomeKit. This api will allow me to perform homekit actions very quickly like light.on() for example.

To follow my explanation and then introduce my issue here is an example of my public class for lights management. This works fine.

public class AIALight: AIAEquipment {

    // MARK: - Initialization
    public init(kind: Kind, name: String) {
        super.init(.light, equipmentName: name)
    }

}

extension AIALight: AIAControllable {

    public enum Order: AIAOrder {

        // MARK: - Values
        case on
        case off

        var info: (Int) {
            switch self {
            case .on:
                return 1
            case .off:
                return 0
            }
        }
    }
}

Then create a light...

var myLight = AIALight(kind: .light, name: "Sdb1")

... and send an order when it's needed doing :

self.myLight.set(.on, completion: nil)

Ok now keeping the same idea I would like to be able to create homes and rooms. For homes HMHomeManagerDelegate and of course HMHomeManager.

Here is my complete own class to create a Home :

import Foundation
import HomeKit

public final class AIAHouse: HMHome, HMHomeManagerDelegate {

    public var house: HMHome!
    public let houseName: String

    public var manager: HMHomeManager? {
        didSet {
            self.manager?.delegate = self
        }
    }

    // MARK: - Initialization
    public init(houseName: String) {
        self.manager = nil
        self.houseName = houseName
    }

    public func homeManagerDidUpdateHomes(_ manager: HMHomeManager) {

        //We browse HMHome to find CruzHouse already set via Home App on iOS
        for home in manager.homes as [HMHome]{
            if home.name == self.houseName{

                print("Found the expected home: \(self.houseName) 🏠")
                self.house = home

            }
            else {
                print("\(self.houseName) not found 🛑")
            }
        }


    }
}

Then in my ViewController :

var homeManager: HMHomeManager!
var myHome: AIAHouse!

override func viewDidLoad() {
        super.viewDidLoad()

        self.homeManager = HMHomeManager()

        self.myHome = AIAHouse(houseName: "MyHome")
        self.myHome.manager = HMHomeManager()

}

My issue is that self.myHome.manager = HMHomeManager() returns nil and I do not understand why really... Any idea ? Thanks a lot in advance!


Solution

  • From the Apple documentation:

    You don’t create homes directly — instead, you create them with the addHome(withName:completionHandler:) method of HMHomeManager.

    Your code will compile if your AIAHouse object inherits from NSObject instead of HMHome.