Homekit

dpearson2699/swift-ios-skills/skills/homekit

作者 dpearson26998d90fd121a26無授權條款1.1K 個星標收錄於 2026年10月8日更新於 2026年10月8日儲存庫2 個月前更新

Control smart-home accessories and commission Matter devices using HomeKit and MatterSupport. Use when managing homes/rooms/accessories, creating action sets or triggers, reading accessory characteristics, onboarding Matter devices, or building a third-party smart-home ecosystem app.

AI 產生的概覽

指導建置 Apple HomeKit 與 MatterSupport 智慧家庭應用,涵蓋配件、場景、觸發條件與 Matter 配網。

功能
此技能為 Apple 的 HomeKit 與 MatterSupport 框架提供參考指引與程式碼範例。內容涵蓋家庭/房間/配件資料模型、讀取與寫入配件特徵值、動作集以及定時或事件觸發條件,並將 Matter 裝置配網到應用生態系中。它也列出常見錯誤與 HomeKit 應用設定的檢查清單。
適用情境
在撰寫或審查透過 HomeKit 管理家庭、房間、配件、場景或觸發條件的 iOS 應用時使用。也適用於透過 MatterSupport 接入 Matter 裝置或建置第三方智慧家庭生態系應用。
執行需求
需要 Apple 開發環境與 Xcode,啟用 HomeKit 能力並在 Info.plist 中加入 NSHomeKitUsageDescription;Matter 配網需要 MatterSupport 擴充目標、Bonjour 服務項目,以及可選的 setup-payload 權限。僅為說明文件,不附帶指令碼。

HomeKit

Control home automation accessories and commission Matter devices. HomeKit manages the home/room/accessory model, action sets, and triggers. MatterSupport handles device commissioning into your ecosystem.

Contents

Setup

HomeKit Configuration

  1. Enable the HomeKit capability in Xcode (Signing & Capabilities)
  2. Add NSHomeKitUsageDescription to Info.plist:
xml
<key>NSHomeKitUsageDescription</key><string>This app controls your smart home accessories.</string>

MatterSupport Configuration

For Matter commissioning into your own ecosystem:

  1. Add a MatterSupport Extension target and set its principal class to a MatterAddDeviceExtensionRequestHandler subclass
  2. Add NSBonjourServices entries for _matter._tcp, _matterc._udp, and _matterd._udp
  3. Add com.apple.developer.matter.allow-setup-payload only if the caller supplies a Matter setup payload programmatically

Framework Boundary

NeedFramework
Homes, rooms, accessories, characteristics, actions, triggersHomeKit
Commission Matter into the app ecosystemMatterSupport
Select and authorize a nearby Bluetooth or Wi-Fi accessoryAccessorySetupKit
Exchange Bluetooth GATT data after selectionCoreBluetooth
Join or configure an accessory's Wi-Fi network after selectionNetworkExtension

HomeKit Data Model

HomeKit organizes home automation in a hierarchy:

text
HMHomeManager  -> HMHome (one or more)       -> HMRoom (rooms in the home)            -> HMAccessory (devices in a room)                 -> HMService (functions: light, thermostat, etc.)                      -> HMCharacteristic (readable/writable values)       -> HMZone (groups of rooms)       -> HMActionSet (grouped actions)       -> HMTrigger (time or event-based triggers)

Initializing the Home Manager

Create a single HMHomeManager and implement the delegate to know when data is loaded. HomeKit loads asynchronously -- do not access homes until the delegate fires.

swift
import HomeKit
final class HomeStore: NSObject, HMHomeManagerDelegate {    let homeManager = HMHomeManager()
    override init() {        super.init()        homeManager.delegate = self    }
    func homeManagerDidUpdateHomes(_ manager: HMHomeManager) {        // Safe to access manager.homes now        let homes = manager.homes        let primaryHome = manager.primaryHome        print("Loaded \(homes.count) homes")    }
    func homeManager(        _ manager: HMHomeManager,        didUpdate status: HMHomeManagerAuthorizationStatus    ) {        if status.contains(.authorized) {            print("HomeKit access granted")        }    }}

Accessing Rooms

swift
guard let home = homeManager.primaryHome else { return }
let rooms = home.roomslet kitchen = rooms.first { $0.name == "Kitchen" }
// Room for accessories not assigned to a specific roomlet defaultRoom = home.roomForEntireHome()

Managing Accessories

Discovering and Adding Accessories

Use the Framework Boundary table before adding an accessory; only HomeKit/MatterSupport work continues in this skill.

swift
// System UI for accessory discoveryhome.addAndSetupAccessories { error in    if let error {        print("Setup failed: \(error)")    }}

Listing Accessories and Services

swift
for accessory in home.accessories {    print("\(accessory.name) in \(accessory.room?.name ?? "unassigned")")
    for service in accessory.services {        print("  Service: \(service.serviceType)")
        for characteristic in service.characteristics {            print("    \(characteristic.characteristicType): \(characteristic.value ?? "nil")")        }    }}

Moving an Accessory to a Room

swift
guard let accessory = home.accessories.first,      let bedroom = home.rooms.first(where: { $0.name == "Bedroom" }) else { return }
home.assignAccessory(accessory, to: bedroom) { error in    if let error {        print("Failed to move accessory: \(error)")    }}

Reading and Writing Characteristics

Reading a Value

swift
let characteristic: HMCharacteristic = // obtained from a service
characteristic.readValue { error in    guard error == nil else { return }    if let value = characteristic.value as? Bool {        print("Power state: \(value)")    }}

Writing a Value

swift
// Turn on a lightcharacteristic.writeValue(true) { error in    if let error {        print("Write failed: \(error)")    }}

Observing Changes

Enable notifications for real-time updates:

swift
characteristic.enableNotification(true) { error in    guard error == nil else { return }}
// In HMAccessoryDelegate:func accessory(    _ accessory: HMAccessory,    service: HMService,    didUpdateValueFor characteristic: HMCharacteristic) {    print("Updated: \(characteristic.value ?? "nil")")}

Action Sets and Triggers

Creating an Action Set

An HMActionSet groups characteristic writes that execute together:

swift
home.addActionSet(withName: "Good Night") { actionSet, error in    guard let actionSet, error == nil else { return }
    // Turn off living room light    let lightChar = livingRoomLight.powerCharacteristic    let action = HMCharacteristicWriteAction(        characteristic: lightChar,        targetValue: false as NSCopying    )    actionSet.addAction(action) { error in        guard error == nil else { return }        print("Action added to Good Night scene")    }}

Executing an Action Set

swift
home.executeActionSet(actionSet) { error in    if let error {        print("Execution failed: \(error)")    }}

Creating a Timer Trigger

swift
var timeOfDay = DateComponents()timeOfDay.hour = 22timeOfDay.minute = 30
let firstFireDate = Calendar.current.nextDate(    after: Date(),    matching: timeOfDay,    matchingPolicy: .nextTime)!
let trigger = HMTimerTrigger(    name: "Nightly",    fireDate: firstFireDate,    recurrence: DateComponents(day: 1)  // Repeat every day after firstFireDate)
home.addTrigger(trigger) { error in    guard error == nil else { return }
    // Attach the action set to the trigger    trigger.addActionSet(goodNightActionSet) { error in        guard error == nil else { return }
        trigger.enable(true) { error in            print("Trigger enabled: \(error == nil)")        }    }}

Creating an Event Trigger

swift
let motionDetected = HMCharacteristicEvent(    characteristic: motionSensorCharacteristic,    triggerValue: true as NSCopying)
let eventTrigger = HMEventTrigger(    name: "Motion Lights",    events: [motionDetected],    predicate: nil)
home.addTrigger(eventTrigger) { error in    // Add action sets as above}

Matter Commissioning

Use MatterAddDeviceRequest to commission a Matter device into your ecosystem. This is separate from the HMHome home-automation model; it handles the Matter setup flow and calls into your MatterSupport extension.

Basic Commissioning

swift
import MatterSupport
func addMatterDevice() async throws {    guard MatterAddDeviceRequest.isSupported else {        print("Matter not supported on this device")        return    }
    let topology = MatterAddDeviceRequest.Topology(        ecosystemName: "My Smart Home",        homes: [            MatterAddDeviceRequest.Home(displayName: "Main House")        ]    )
    let request = MatterAddDeviceRequest(        topology: topology,        setupPayload: nil,        showing: .allDevices    )
    // Presents system UI for device pairing    try await request.perform()}

When providing a setup code directly, import Matter and pass an MTRSetupPayload as setupPayload; this is the case that requires the setup-payload entitlement.

Filtering Devices

swift
// Only show devices from a specific vendorlet criteria = MatterAddDeviceRequest.DeviceCriteria.vendorID(0x1234)
let request = MatterAddDeviceRequest(    topology: topology,    setupPayload: nil,    showing: criteria)

Combine criteria with .all([.vendorID(...), .not(.productID(...))]) or use .any(...) when any one criterion is enough.

MatterAddDeviceExtensionRequestHandler

For full ecosystem support, create a MatterSupport Extension. The extension handles commissioning callbacks. Override the needed methods, but do not call super from those overrides. Load the complete Advanced Matter Extension Handler [blocked] for credential validation, room selection, configuration, commissioning, and network-association overrides.

Common Mistakes

MistakeFix
Reading homes before the delegate updateCreate one manager, set its delegate, and wait for homeManagerDidUpdateHomes.
HomeKit setup is used for Matter ecosystem commissioningUse MatterAddDeviceRequest plus the configured MatterSupport extension.
Matter configuration is incompleteVerify principal handler, Bonjour services, and the setup-payload entitlement only when applicable.
Multiple HMHomeManager instances load the databaseShare one retained manager/store.
Characteristic write ignores metadataCheck permissions, format, min/max/step, and allowed values before writing.

Review Checklist

  • HomeKit capability enabled in Xcode
  • NSHomeKitUsageDescription present in Info.plist
  • Single HMHomeManager instance shared across the app
  • HMHomeManagerDelegate implemented; homes not accessed before homeManagerDidUpdateHomes
  • HMHomeDelegate set on homes to receive accessory and room changes
  • HMAccessoryDelegate set on accessories to receive characteristic updates
  • Characteristic metadata checked before writing values
  • Error handling in all completion handlers
  • MatterSupport extension target and principal handler configured
  • Matter discovery NSBonjourServices entries added
  • com.apple.developer.matter.allow-setup-payload used only when providing setup codes
  • MatterAddDeviceRequest.isSupported checked before performing requests
  • Matter extension handler implements commissionDevice(in:onboardingPayload:commissioningID:)
  • Action sets tested with the HomeKit Accessory Simulator before shipping
  • Triggers enabled after creation (trigger.enable(true))

References

來源與署名

來源:dpearson2699/swift-ios-skills位於skills/homekit提交8d90fd1

授權條款: 無授權條款

內容歸原作者所有。SourceWeft 從公開儲存庫中收錄這些內容。

檢舉或申請下架

更多來自 dpearson2699/swift-ios-skills 的技能

Widgetkit

dpearson2699

指導實作、審查與改進 iOS、iPadOS、watchOS 與 CarPlay 上的 WidgetKit 小工具與控制項。

Software Development1.1K2 個月前更新

Weatherkit

dpearson2699

指導 iOS 開發者使用 WeatherService 取得 WeatherKit 預報、警報與署名資訊。

Software Development1.1K2 個月前更新

Vision Framework

dpearson2699

Implement computer vision features including text recognition (OCR), face detection, barcode scanning, image segmentation, object tracking, and document scanning in iOS apps. Covers both the modern Swift-native Vision API (iOS 18+) and legacy VNRequest patterns, VisionKit DataScannerViewController for live camera scanning, and CoreMLRequest/VNCoreMLRequest for custom model inference. Use when adding OCR, barcode scanning, face detection, or custom Core ML model inference with Vision.

待分類1.1K2 個月前更新

Tipkit

dpearson2699

Implement and review Apple TipKit feature-discovery UI for iOS 17+ apps. Use when adding or auditing in-app tips, contextual help, coach marks, Tip, TipView, popoverTip, rules, events, actions, display frequency, testing overrides, reusable tip identifiers, or iOS 18+ TipGroup and CloudKit tip sync; avoid for generic SwiftUI navigation or layout outside tip presentation.

待分類1.1K2 個月前更新

Tabletopkit

dpearson2699

指導使用 TabletopKit 在 visionOS 上打造多人空間桌遊,涵蓋棋具、座位、動作與 RealityKit 算繪。

Software Development1.1K2 個月前更新

Swiftui Webkit

dpearson2699

指導在 iOS 26 及更新版本的 SwiftUI App 中使用 WebKit for SwiftUI 嵌入與控制網頁內容。

Software Development1.1K2 個月前更新