Поиск устройства
Запросите на подключённом устройстве предусмотренную прошивкой индикацию поиска. Этот API помогает найти конкретное устройство, а не выполняет поиск ближайших Bluetooth-устройств.
Предварительные условия
Перед вызовом API убедитесь, что:
- Устройство подключено и готово.
- Устройство поддерживает протокол
DeviceFindAPI.
Справочник API
Фреймворк
AIBuds.xcframework
Импорт
- Swift
- Objective-C
import AIBuds#import <AIBuds/AIBuds-Swift.h>
#import <AIBuds/AIBuds.h>Протокол
Метод findDevice объявлен в DeviceFindAPI.
- Swift
- Objective-C
/// Controls the locate-device indication on a connected device.
///
/// This API operates on the device represented by the conforming object. It
/// does not perform Bluetooth discovery or scan for nearby devices. The
/// indication used to locate the device, such as sound, vibration, or another
/// firmware-defined behavior, depends on the device implementation.
///
/// A successful completion from `findDevice(_:)` means the start command was
/// accepted; it does not mean the device has been physically located. Observe
/// `DeviceDelegate.deviceDidReportFound(_:)` or
/// `SDKDelegate.deviceDidReportFound(_:)` when the device supports reporting
/// that it has been found.
public protocol DeviceFindAPI: DeviceAPI {
/// Requests that the connected device start its locate-device indication.
///
/// The completion reports whether the command was accepted and executed by
/// the device. It does not report whether the user has located the device.
/// Use `DeviceDelegate.deviceDidReportFound(_:)` or the corresponding
/// `SDKDelegate` callback for a device-originated found event.
/// - Parameters:
/// - completion: Called when command processing completes.
/// - success: `true` when the device accepted the command; otherwise,
/// `false`.
/// - error: The command or communication error, or `nil` on success.
func findDevice(_ completion: AIBudsCompletionHandler?)
}/// Controls the locate-device indication on a connected device.
///
/// This API operates on the device represented by the conforming object. It
/// does not perform Bluetooth discovery or scan for nearby devices. A
/// successful completion means command acceptance, not physical location.
@protocol AIBudsDeviceFindAPI <AIBudsDeviceAPI>
/// Requests that the connected device start its locate-device indication.
///
/// The completion reports command processing. A supported device reports
/// the terminal found event separately through the device or SDK delegate.
/// - Parameters:
/// - completion: Called when command processing completes.
/// - success: `true` when the device accepted the command; otherwise,
/// `false`.
/// - error: The command or communication error, or `nil` on success.
- (void)findDeviceWithCompletion:(AIBudsCompletionHandler _Nullable)completion;
@endМетод экземпляра
Запрашивает запуск индикации поиска на подключённом устройстве.
- Swift
- Objective-C
/// Requests that the connected device start its locate-device indication.
///
/// The completion reports whether the command was accepted and executed by
/// the device. It does not report whether the user has located the device.
/// Use `DeviceDelegate.deviceDidReportFound(_:)` or the corresponding
/// `SDKDelegate` callback for a device-originated found event.
/// - Parameters:
/// - completion: Called when command processing completes.
/// - success: `true` when the device accepted the command; otherwise,
/// `false`.
/// - error: The command or communication error, or `nil` on success.
func findDevice(_ completion: AIBudsCompletionHandler?)/// Requests that the connected device start its locate-device indication.
///
/// The completion reports command processing. A supported device reports the
/// terminal found event separately through the device or SDK delegate.
/// - Parameters:
/// - completion: Called when command processing completes.
/// - success: `true` when the device accepted the command; otherwise,
/// `false`.
/// - error: The command or communication error, or `nil` on success.
- (void)findDeviceWithCompletion:(AIBudsCompletionHandler _Nullable)completion;Параметры
| Параметр | Тип | Описание |
|---|---|---|
completion | AIBudsCompletionHandler? | Необязательный обработчик, вызываемый после обработки команды. |
Параметры обратного вызова:
| Имя | Тип | Описание |
|---|---|---|
success | Bool / BOOL | true, если устройство приняло команду; иначе false. |
error | NSError? | Ошибка команды или связи; при успехе — nil. |
Возвращаемое значение
Метод не возвращает значение напрямую. Обработчик сообщает об обработке команды, а не о том, что пользователь действительно нашёл устройство.
Примеры использования
- Swift
- Objective-C
import AIBuds
final class DeviceManager {
weak var device: DeviceConvertible?
func startFindingDevice() {
guard let device = device as? DeviceFindAPI else {
print("Device does not support finding")
return
}
device.findDevice { success, error in
guard success else {
print("Failed to start finding: \(error?.localizedDescription ?? "Unknown error")")
return
}
print("Locate-device command accepted")
}
}
}#import <AIBuds/AIBuds-Swift.h>
#import <AIBuds/AIBuds.h>
id<AIBudsDeviceFindAPI> device = (id<AIBudsDeviceFindAPI>)self.device;
if (![device conformsToProtocol:@protocol(AIBudsDeviceFindAPI)]) {
NSLog(@"Device does not support finding");
return;
}
[device findDeviceWithCompletion:^(BOOL success, NSError *_Nullable error) {
if (!success) {
NSLog(@"Failed to start finding: %@", error.localizedDescription ?: @"Unknown error");
return;
}
NSLog(@"Locate-device command accepted");
}];Событие обнаружения устройства
Если устройство поддерживает эту возможность, deviceDidReportFound служит отдельным итоговым событием от устройства:
- Swift
- Objective-C
/// Called when the device reports that it has been found.
///
/// This is distinct from `findDevice(_:)` completion, which only reports
/// command processing.
func deviceDidReportFound(_ device: DeviceConvertible) {
DispatchQueue.main.async {
self.showDeviceFoundState()
}
}/// Called when the device reports that it has been found.
///
/// This is distinct from the find command completion, which only reports
/// command processing.
- (void)deviceDidReportFound:(id<AIBudsDeviceConvertible>)device {
dispatch_async(dispatch_get_main_queue(), ^{
[self showDeviceFoundState];
});
}Обработка ошибок
Показывайте принятие команды только после проверки success, а ошибки команды и связи берите из error. Успешная обработка команды не означает, что устройство найдено: если поддерживается отдельное событие обнаружения, дождитесь его.
Рекомендации
- Проверяйте соответствие протоколу: перед вызовом метода убедитесь в поддержке
DeviceFindAPI. - Точно обозначайте состояние: различайте «команда принята» и «устройство найдено».
- Предусмотрите остановку: после запуска индикации сделайте доступным
stopFindDevice(_:). - Обрабатывайте событие обнаружения: реализуйте обратный вызов делегата устройства или SDK, если он поддерживается.
- Обновляйте UI в главной очереди: направляйте обновления UIKit из обработчиков и делегатов в главную очередь.
Примечания
- API управляет уже подключённым устройством и не выполняет обнаружение или сканирование.
- Публичный API определяет индикацию поиска, но не задаёт способ её отображения устройством.
- Звук, вибрация, длительность и громкость зависят от устройства.
- Обратный сценарий поиска iPhone описан в разделе «Сообщение о найденном iPhone».