Перейти к основному содержимому

Настройка распознавания ношения

Включайте или выключайте распознавание ношения, когда устройство сообщает о возможности настройки.

Предварительные условия

  • Устройство подключено и готово к работе.
  • Устройство поддерживает DeviceWearDetectionAPI.
  • wearDetectionCapability равно .supportedAndConfigurable.

Справочник API

Фреймворк

AIBuds.xcframework

Импорт

Swift
import AIBuds

Протокол

Метод определён протоколом DeviceWearDetectionAPI.

Swift
/// The protocol for device wear detection API.
protocol DeviceWearDetectionAPI: DeviceAPI {
    /// Enable or disable wear-detection functionality
    /// - Parameters:
    ///   - enabled: Whether to enable wear detection
    ///   - completion: A closure that is called when the operation completes.
    ///     - success: `true` if the operation was successful; otherwise `false`.
    ///     - error: An `NSError` object that describes the error that occurred, or `nil` if the operation was successful.
    func setWearDetection(
        enabled: Bool,
        completion: AIBudsCompletionHandler?
    )
}

Метод экземпляра

Включает или выключает распознавание ношения.

Открыть setWearDetection в справочнике API.
Swift
/// Enable or disable wear-detection functionality
/// - Parameters:
///   - enabled: Whether to enable wear detection
///   - completion: A closure that is called when the operation completes.
///     - success: `true` if the operation was successful; otherwise `false`.
///     - error: An `NSError` object that describes the error that occurred, or `nil` if the operation was successful.
func setWearDetection(
    enabled: Bool,
    completion: AIBudsCompletionHandler?
)

Параметры

ПараметрТипОписание
enabledBool / BOOLtrue/YES включает функцию, иначе выключает.
completionAIBudsCompletionHandler?Необязательный обработчик завершения операции.

Параметры обработчика:

ИмяТипОписание
successBool / BOOLУспешно ли выполнена операция.
errorNSError?Сведения об ошибке или nil при успехе.

Возвращаемое значение

Метод не возвращает значение напрямую.

Примеры использования

Swift
import AIBuds

guard let device = device as? DeviceWearDetectionAPI else {
    print("Device does not support wear detection")
    return
}

guard device.wearDetectionCapability == .supportedAndConfigurable else {
    print("Wear detection is not configurable")
    return
}

device.setWearDetection(enabled: true) { success, error in
    guard success else {
        print("Failed to enable wear detection: \(error?.localizedDescription ?? "Unknown error")")
        return
    }
    print("Wear detection enabled")
}

Обработка ошибок

Перед обновлением интерфейса проверьте success, а детали ошибки получите из error. Не вызывайте метод при .none или .supportedNotConfigurable.

Рекомендации

  1. Проверяйте возможность: отправляйте команду только при .supportedAndConfigurable.
  2. Избегайте лишних команд: сначала сравните значение с isWearDetectionEnabled.
  3. Обновляйтесь после успеха: прочитайте текущее свойство или дождитесь didWearDetectionEnabledChanged до отображения применённого состояния.

Примечания

  • Demo SDK выполняет такую же проверку возможности перед включением или выключением.
  • Метод не определяет автоматическую паузу или продолжение музыки.