Accessorysetupkit

dpearson2699/swift-ios-skills/skills/accessorysetupkit

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

Discover and configure Bluetooth and Wi-Fi accessories using AccessorySetupKit. Use when presenting a privacy-preserving accessory picker, defining discovery descriptors for BLE or Wi-Fi devices, handling accessory session events, migrating from CoreBluetooth permission-based scanning, or setting up accessories without requiring broad Bluetooth permissions.

AI 產生的概覽

指導 iOS 開發者使用 AccessorySetupKit,以保護隱私的方式探索與設定藍牙及 Wi-Fi 配件。

功能
此技能為在 iOS 18 以上版本使用 Apple 的 AccessorySetupKit 框架提供參考指引。內容涵蓋 Info.plist 權限設定、藍牙與 Wi-Fi 的 ASDiscoveryDescriptor 比對規則、顯示系統配件選擇器、處理 ASAccessorySession 事件,以及交接給 CoreBluetooth 或 NetworkExtension。它也記錄了從 CoreBluetooth 以權限為基礎的掃描進行移轉、常見錯誤與審查清單。
適用情境
適用於建置透過系統選擇器配對藍牙或 Wi-Fi 配件、且不需要廣泛藍牙權限的 iOS 應用程式。也適用於定義探索描述元、處理配件工作階段事件,或將現有 CoreBluetooth 配件移轉至 AccessorySetupKit。
執行需求
需要 iOS 18 或更新版本以及 Apple 的 AccessorySetupKit 框架,並搭配 CoreBluetooth 與 NetworkExtension 進行配對後通訊。必須設定 NSAccessorySetupSupports 等 Info.plist 鍵值。不包含指令碼,此技能僅為說明與參考文件。

AccessorySetupKit

Use the iOS 18+ system picker for privacy-preserving Bluetooth/Wi-Fi accessory discovery and authorization, then hand off communication to CoreBluetooth or NetworkExtension.

Contents

Setup and Entitlements

Info.plist Configuration

Add these keys to the app's Info.plist:

KeyTypePurpose
NSAccessorySetupSupports[String]Required. Array containing Bluetooth and/or WiFi
NSAccessorySetupBluetoothServices[String]Service UUIDs the app discovers (Bluetooth)
NSAccessorySetupBluetoothNames[String]Bluetooth names or substrings to match
NSAccessorySetupBluetoothCompanyIdentifiers[String]Two-byte Bluetooth company identifiers

The Bluetooth-specific keys must match the values used in ASDiscoveryDescriptor. If the app uses identifiers, names, or services not declared in Info.plist, the app crashes during AccessorySetupKit discovery. For Wi-Fi accessories, include WiFi in NSAccessorySetupSupports and match the descriptor's SSID rule.

No Bluetooth Permission Required

When an app declares NSAccessorySetupSupports with Bluetooth, creating a CBCentralManager no longer triggers the system Bluetooth permission dialog. The central manager's state transitions to poweredOn only when the app has at least one paired accessory via AccessorySetupKit.

Discovery Descriptors

ASDiscoveryDescriptor defines the matching criteria for finding accessories. The system matches scanned results against all rules in the descriptor to filter for the target accessory.

Bluetooth Descriptor

swift
import AccessorySetupKitimport CoreBluetooth
var descriptor = ASDiscoveryDescriptor()descriptor.bluetoothServiceUUID = CBUUID(string: "12345678-1234-1234-1234-123456789ABC")descriptor.bluetoothNameSubstring = "MyDevice"descriptor.bluetoothRange = .immediate  // Only nearby devices

A Bluetooth descriptor needs at least one of bluetoothCompanyIdentifier or bluetoothServiceUUID. Add narrower matchers as needed:

  • bluetoothNameSubstring with a company identifier or service UUID
  • bluetoothManufacturerDataBlob and bluetoothManufacturerDataMask with a company identifier; blob and mask must have the same length
  • bluetoothServiceDataBlob and bluetoothServiceDataMask with a service UUID; blob and mask must have the same length

Wi-Fi Descriptor

swift
var descriptor = ASDiscoveryDescriptor()descriptor.ssid = "MyAccessory-Network"// OR use a prefix:// descriptor.ssidPrefix = "MyAccessory-"

Supply either ssid or ssidPrefix, not both. The app crashes if both are set. The ssidPrefix must have a non-zero length.

Bluetooth Range

Control the physical proximity required for discovery:

ValueBehavior
.defaultStandard Bluetooth range
.immediateOnly accessories in close physical proximity

Support Options

Set supportedOptions on the descriptor to declare the accessory's capabilities:

swift
descriptor.supportedOptions = [.bluetoothPairingLE, .bluetoothTransportBridging]
OptionPurpose
.bluetoothPairingLEBLE pairing support
.bluetoothTransportBridgingBluetooth transport bridging
.bluetoothHIDBluetooth HID device

Presenting the Picker

Creating the Session

Create and activate an ASAccessorySession to manage discovery lifecycle. Wait for .activated before reading session.accessories or presenting the picker:

swift
import AccessorySetupKit
final class AccessoryManager {    private let session = ASAccessorySession()
    func start() {        session.activate(on: .main) { [weak self] event in            self?.handleEvent(event)        }    }
    private func handleEvent(_ event: ASAccessoryEvent) {        switch event.eventType {        case .activated:            // Session ready. Check session.accessories for previously paired devices.            break        case .accessoryAdded:            guard let accessory = event.accessory else { return }            handleAccessoryAdded(accessory)        case .accessoryChanged:            // Accessory properties changed (e.g., display name updated in Settings)            break        case .accessoryRemoved:            // Accessory removed by user or app            break        case .invalidated:            // Session invalidated, cannot be reused            break        @unknown default:            break        }    }}

Showing the Picker

Create ASPickerDisplayItem instances with a name, product image, and discovery descriptor, then pass them to the activated session:

swift
func showAccessoryPicker() {    var descriptor = ASDiscoveryDescriptor()    descriptor.bluetoothServiceUUID = CBUUID(string: "ABCD1234-0000-1000-8000-00805F9B34FB")
    guard let image = UIImage(named: "my-accessory") else { return }
    let item = ASPickerDisplayItem(        name: "My Bluetooth Accessory",        productImage: image,        descriptor: descriptor    )
    session.showPicker(for: [item]) { error in        if let error {            print("Picker failed: \(error.localizedDescription)")        }    }}

The picker runs in a separate system process. It shows each matching device as a separate item. When multiple devices match a given descriptor, the picker creates a horizontal carousel.

Setup Options

Configure picker behavior per display item:

swift
var item = ASPickerDisplayItem(    name: "My Accessory",    productImage: image,    descriptor: descriptor)item.setupOptions = [.rename, .confirmAuthorization]
OptionEffect
.renameAllow renaming the accessory during setup
.confirmAuthorizationShow authorization confirmation before setup
.finishInAppSignal that setup continues in the app after pairing

Product Images

The picker displays images in a 180x120 point container. Best practices:

  • Use high-resolution images for all screen scale factors
  • Use transparent backgrounds for correct light/dark mode appearance
  • Adjust transparent borders as padding to control apparent accessory size
  • Test in both light and dark mode

Event Handling

Event Types

The session delivers ASAccessoryEvent objects through the event handler:

EventWhen
.activatedSession is active, query session.accessories
.accessoryAddedUser selected an accessory in the picker
.accessoryChangedAccessory properties updated (e.g., renamed)
.accessoryRemovedAccessory removed from system
.invalidatedSession invalidated, create a new one
.migrationCompleteMigration of legacy accessories completed
.pickerDidPresentPicker appeared on screen
.pickerDidDismissPicker dismissed
.pickerSetupBridgingTransport bridging setup in progress
.pickerSetupPairingBluetooth pairing in progress
.pickerSetupFailedSetup failed
.pickerSetupRenameUser is renaming the accessory
.accessoryDiscoveredNew accessory found (custom filtering mode)

Coordinating Picker Dismissal

When the user selects an accessory, .accessoryAdded fires before .pickerDidDismiss. To show custom setup UI after the picker closes, store the accessory on the first event and act on it after dismissal:

swift
private var pendingAccessory: ASAccessory?
private func handleEvent(_ event: ASAccessoryEvent) {    switch event.eventType {    case .accessoryAdded:        pendingAccessory = event.accessory    case .pickerDidDismiss:        if let accessory = pendingAccessory {            pendingAccessory = nil            beginCustomSetup(accessory)        }    @unknown default:        break    }}

Bluetooth Accessories

After an accessory is added via the picker, use CoreBluetooth to communicate. The bluetoothIdentifier on the ASAccessory maps to a CBPeripheral.

swift
import CoreBluetooth
func handleAccessoryAdded(_ accessory: ASAccessory) {    guard let btIdentifier = accessory.bluetoothIdentifier else { return }
    // Create CBCentralManager — no Bluetooth permission prompt appears    let centralManager = CBCentralManager(delegate: self, queue: nil)
    // After poweredOn, retrieve the peripheral    let peripherals = centralManager.retrievePeripherals(        withIdentifiers: [btIdentifier]    )    guard let peripheral = peripherals.first else { return }    centralManager.connect(peripheral, options: nil)}

Key points:

  • CBCentralManager state reaches .poweredOn only when the app has paired accessories
  • Scanning with scanForPeripherals(withServices:) returns only accessories paired through AccessorySetupKit
  • No NSBluetoothAlwaysUsageDescription is needed when using AccessorySetupKit exclusively

Wi-Fi Accessories

For Wi-Fi accessories, the ssid on the ASAccessory identifies the network. Use NEHotspotConfiguration from NetworkExtension to join it:

swift
import NetworkExtension
func handleWiFiAccessoryAdded(_ accessory: ASAccessory) {    guard let ssid = accessory.ssid else { return }
    let configuration = NEHotspotConfiguration(ssid: ssid)    NEHotspotConfigurationManager.shared.apply(configuration) { error in        if let error {            print("Wi-Fi join failed: \(error.localizedDescription)")        }    }}

Because the accessory was discovered through AccessorySetupKit, joining the network does not trigger the standard Wi-Fi access prompt.

Migration from CoreBluetooth

Apps with existing CoreBluetooth-authorized accessories can migrate them to AccessorySetupKit using ASMigrationDisplayItem. This is a one-time operation that registers known accessories in the new system.

swift
func migrateExistingAccessories() {    guard let image = UIImage(named: "my-accessory") else { return }
    var descriptor = ASDiscoveryDescriptor()    descriptor.bluetoothServiceUUID = CBUUID(string: "ABCD1234-0000-1000-8000-00805F9B34FB")
    let migrationItem = ASMigrationDisplayItem(        name: "My Accessory",        productImage: image,        descriptor: descriptor    )    // Set the peripheral identifier from CoreBluetooth    migrationItem.peripheralIdentifier = existingPeripheralUUID
    // For Wi-Fi accessories:    // migrationItem.hotspotSSID = "MyAccessory-WiFi"
    session.showPicker(for: [migrationItem]) { error in        if let error {            print("Migration failed: \(error.localizedDescription)")        }    }}

Migration rules:

  • If showPicker contains only migration items, the system shows an informational page instead of a discovery picker
  • If migration items are mixed with regular display items, migration happens only when a new accessory is discovered and set up
  • Do not initialize CBCentralManager before migration completes — doing so causes an error and the picker fails to appear
  • The session receives .migrationComplete when migration finishes

Common Mistakes

MistakeFix
Descriptor identifiers are absent from Info.plistDeclare every Bluetooth service, name, and company identifier before presenting the picker.
Both ssid and ssidPrefix are setChoose exactly one matching strategy.
CoreBluetooth starts before migration completesWait for .migrationComplete, then create CBCentralManager.
Picker appears without explicit user intentPresent it only from a user action.
An invalidated session is reusedCreate, activate, and retain a new ASAccessorySession.

Review Checklist

  • NSAccessorySetupSupports added to Info.plist with Bluetooth and/or WiFi
  • Session activated before calling showPicker
  • Event handler uses [weak self] to avoid retain cycles
  • All ASAccessoryEventType cases handled, including @unknown default
  • Product images use transparent backgrounds and appropriate resolution
  • bluetoothIdentifier or ssid from ASAccessory used to connect post-setup
  • Accessory removal events handled to clean up app state

References

來源與署名

來源:dpearson2699/swift-ios-skills位於skills/accessorysetupkit提交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 個月前更新