I'm developing a SwiftUI app for iOS and iPadOS to control my HomeKit smart devices, especially a RGB led strip. I have downloaded the accessory simulator and I have created two accessories named "Plug" and "Led Strip". I'm following this official documentation and I was able to create and to remove new homes using this code:
class HomeStore: NSObject {
static var shared = HomeStore()
let homeManager = HMHomeManager()
var homeDelegates = Set<NSObject>()
var accessoryDelegates = Set<NSObject>()
}
extension HomeStore: HMHomeManagerDelegate {
func addHome(name: String) {
homeManager.addHome(withName: name, completionHandler: { (home, error) in
if let error = error {
print("Error while adding a new home named \(name): \(error.localizedDescription)")
}
})
}
func removeHome(homeName: String) {
homeManager.homes.forEach({ home in
if (home.name == homeName) {
homeManager.removeHome(home, completionHandler: { error in
if let error = error {
print("Error while removing home named \(homeName): \(error.localizedDescription)")
}
})
}
})
}
I created another function to search new accessories:
func searchAccessories() -> [HMAccessory] {
accessoryBrowser.startSearchingForNewAccessories()
accessoryBrowser.stopSearchingForNewAccessories()
return accessoryBrowser.discoveredAccessories
}
If I run this function above it searches for new accessories and show me them in this SwiftUI View:
var body: some View {
Form {
ForEach(homeStore.searchAccessories()) { accessory in
Section {
Text(accessory.name)
Button("Add", action: {
homeStore.addAccessory(accessory: accessory, to: home)
})
}
}
}
}
When I press on "Add" button it runs the following function:
func addAccessory(home: HMHome, accessory: HMAccessory) {
home.addAccessory(accessory, completionHandler: { error in
if let error = error {
print("Error while adding a new accessory named \(accessory.name) to home \(home.name): \(error.localizedDescription)")
}
})
}
But it gives me the following error:
Error while adding a new accessory named Led Strip to home Casa: Object not found.
I tried also adding manually HomeKit-URL (of the type X-ME://ect..) with the following function:
func addAccessory(name: String, to home: HMHome, to room: HMRoom, url: URL) {
let request = HMAccessorySetupRequest()
request.suggestedAccessoryName = name
request.homeUniqueIdentifier = home.uniqueIdentifier
request.suggestedRoomUniqueIdentifier = room.uniqueIdentifier
request.payload = HMAccessorySetupPayload(url: url)
let setupManager = HMAccessorySetupManager()
setupManager.performAccessorySetup(using: request, completionHandler: { result, error in
if let error = error {
print("Error while adding accessory named \(name) to home \(home.name), room \(room.name): \(error.localizedDescription)")
}
})
}
But it gives me error 17: insufficient privileges for the operation.

so this could be because you haven't downloaded the
HomeKit Simulatorthere's an apple doc here on how to do that. It essentially aids in developing and testing HomeKit Accessories.