跳到主要内容

设置佩戴检测

当设备报告支持配置时,启用或禁用佩戴检测。

前提条件

  • 设备已连接并就绪。
  • 设备支持 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?
    )
}

实例方法

启用或禁用佩戴检测。

在 API Reference 中打开 setWearDetection
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?操作完成时调用的可选完成 Handler。

回调参数:

名称类型说明
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")
}

错误处理

更新本地 UI 前检查 success,并通过 error 获取失败详情。当能力为 .none.supportedNotConfigurable 时不要调用该方法。

最佳实践

  1. 验证能力:发送指令前必须确认能力为 .supportedAndConfigurable
  2. 避免重复指令:先将请求值与 isWearDetectionEnabled 比较。
  3. 成功后刷新:读取当前属性或等待 didWearDetectionEnabledChanged,再展示已应用状态。

注意事项

  • SDK Demo 在启用或禁用佩戴检测前会执行相同的能力检查。
  • 该方法没有定义自动暂停或恢复音乐的行为。