Настройка распознавания ношения
Включайте или выключайте распознавание ношения, когда устройство сообщает о возможности настройки.
Предварительные условия
- Устройство подключено и готово к работе.
- Устройство поддерживает
DeviceWearDetectionAPI. wearDetectionCapabilityравно.supportedAndConfigurable.
Справочник API
Фреймворк
AIBuds.xcframework
Импорт
- Swift
- Objective-C
import AIBuds#import <AIBuds/AIBuds-Swift.h>
#import <AIBuds/AIBuds.h>Протокол
Метод определён протоколом DeviceWearDetectionAPI.
- Swift
- Objective-C
/// 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?
)
}/// The protocol for device wear detection API.
@protocol AIBudsDeviceWearDetectionAPI <AIBudsDeviceAPI>
/// 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.
- (void)setWearDetectionEnabled:(BOOL)enabled
completion:(AIBudsCompletionHandler _Nullable)completion;
@endМетод экземпляра
Включает или выключает распознавание ношения.
ОткрытьsetWearDetection в справочнике API.
- Swift
- Objective-C
/// 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?
)/// 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.
- (void)setWearDetectionEnabled:(BOOL)enabled
completion:(AIBudsCompletionHandler _Nullable)completion;Параметры
| Параметр | Тип | Описание |
|---|---|---|
enabled | Bool / BOOL | true/YES включает функцию, иначе выключает. |
completion | AIBudsCompletionHandler? | Необязательный обработчик завершения операции. |
Параметры обработчика:
| Имя | Тип | Описание |
|---|---|---|
success | Bool / BOOL | Успешно ли выполнена операция. |
error | NSError? | Сведения об ошибке или nil при успехе. |
Возвращаемое значение
Метод не возвращает значение напрямую.
Примеры использования
- Swift
- Objective-C
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")
}#import <AIBuds/AIBuds-Swift.h>
#import <AIBuds/AIBuds.h>
id<AIBudsDeviceWearDetectionAPI> device = (id<AIBudsDeviceWearDetectionAPI>)self.device;
if (![device conformsToProtocol:@protocol(AIBudsDeviceWearDetectionAPI)]) {
return;
}
if (device.wearDetectionCapability != AIBudsWearDetectionCapabilitySupportedAndConfigurable) {
NSLog(@"Wear detection is not configurable");
return;
}
[device
setWearDetectionEnabled:YES
completion:^(BOOL success, NSError *_Nullable error) {
if (!success) {
NSLog(@"Failed to enable wear detection: %@", error.localizedDescription);
return;
}
NSLog(@"Wear detection enabled");
}];Обработка ошибок
Перед обновлением интерфейса проверьте success, а детали ошибки получите из error. Не вызывайте метод при .none или .supportedNotConfigurable.
Рекомендации
- Проверяйте возможность: отправляйте команду только при
.supportedAndConfigurable. - Избегайте лишних команд: сначала сравните значение с
isWearDetectionEnabled. - Обновляйтесь после успеха: прочитайте текущее свойство или дождитесь
didWearDetectionEnabledChangedдо отображения применённого состояния.
Примечания
- Demo SDK выполняет такую же проверку возможности перед включением или выключением.
- Метод не определяет автоматическую паузу или продолжение музыки.