Сообщение о найденном iPhone
Обработайте инициированный устройством запрос поиска iPhone, управляйте сигналом на стороне iPhone и сообщите устройству, когда пользователь найдёт телефон.
Это обратный сценарий по отношению к поиску устройства: процесс запускает подключённое устройство, а звук, вибрацию и интерфейс для поиска iPhone реализует приложение.
Предварительные условия
Перед сообщением о найденном iPhone убедитесь, что:
- Запросившее поиск устройство остаётся подключённым и готовым.
- Приложение обрабатывает
deviceDidRequestStartFindingPhoneиdeviceDidRequestStopFindingPhoneлибо соответствующие обратные вызовыSDKDelegate. - Устройство поддерживает
FindPhoneStateReportingAPI. - После подтверждения пользователем приложение остановило индикацию на iPhone.
Справочник API
Фреймворк
AIBuds.xcframework
Импорт
- Swift
- Objective-C
import AIBuds#import <AIBuds/AIBuds-Swift.h>
#import <AIBuds/AIBuds.h>Протокол
Метод notifyPhoneFound объявлен в FindPhoneStateReportingAPI.
- Swift
- Objective-C
/// Reports to a connected device that its find-phone request has been resolved.
///
/// Find-phone is initiated by the device rather than by this API. Observe
/// `DeviceDelegate.deviceDidRequestStartFindingPhone(_:)` and
/// `DeviceDelegate.deviceDidRequestStopFindingPhone(_:)`, or the corresponding
/// `SDKDelegate` callbacks, to start and stop the app's phone-side alert.
///
/// After the user locates the phone, call `notifyPhoneFound(_:)` to notify the
/// requesting device. To make the connected device itself emit a locate
/// indication, use `DeviceFindAPI` instead.
public protocol FindPhoneStateReportingAPI: DeviceAPI {
/// Notifies the connected device that the user has found the phone.
///
/// Call this after handling a device-originated find-phone request and
/// stopping the phone-side alert. The completion reports delivery and
/// command processing; it does not represent a new find-phone request.
/// - Parameters:
/// - completion: Called when command processing completes.
/// - success: `true` when the device accepted the report; otherwise,
/// `false`.
/// - error: The command or communication error, or `nil` on success.
func notifyPhoneFound(_ completion: AIBudsCompletionHandler?)
}/// Reports to a connected device that its find-phone request has been resolved.
///
/// Find-phone is initiated by the device. Observe the device or SDK delegate
/// callbacks to start and stop the app's phone-side alert.
@protocol AIBudsFindPhoneStateReportingAPI <AIBudsDeviceAPI>
/// Notifies the connected device that the user has found the phone.
///
/// Call this after stopping the phone-side alert. The completion reports
/// delivery and command processing; it does not start a new request.
/// - Parameters:
/// - completion: Called when command processing completes.
/// - success: `true` when the device accepted the report; otherwise,
/// `false`.
/// - error: The command or communication error, or `nil` on success.
- (void)notifyPhoneFoundWithCompletion:(AIBudsCompletionHandler _Nullable)completion;
@endМетод экземпляра
Сообщает подключённому устройству, что пользователь нашёл iPhone.
- Swift
- Objective-C
/// Notifies the connected device that the user has found the phone.
///
/// Call this after handling a device-originated find-phone request and
/// stopping the phone-side alert. The completion reports delivery and
/// command processing; it does not represent a new find-phone request.
/// - Parameters:
/// - completion: Called when command processing completes.
/// - success: `true` when the device accepted the report; otherwise,
/// `false`.
/// - error: The command or communication error, or `nil` on success.
func notifyPhoneFound(_ completion: AIBudsCompletionHandler?)/// Notifies the connected device that the user has found the phone.
///
/// Call this after stopping the phone-side alert. The completion reports
/// delivery and command processing; it does not start a new request.
/// - Parameters:
/// - completion: Called when command processing completes.
/// - success: `true` when the device accepted the report; otherwise,
/// `false`.
/// - error: The command or communication error, or `nil` on success.
- (void)notifyPhoneFoundWithCompletion:(AIBudsCompletionHandler _Nullable)completion;См. notifyPhoneFound в справочнике API.
Параметры
| Параметр | Тип | Описание |
|---|---|---|
completion | AIBudsCompletionHandler? | Необязательный обработчик, вызываемый после доставки отчёта и обработки команды. |
Параметры обратного вызова:
| Имя | Тип | Описание |
|---|---|---|
success | Bool / BOOL | true, если устройство приняло сообщение о найденном iPhone; иначе false. |
error | NSError? | Ошибка команды или связи; при успехе — nil. |
Возвращаемое значение
Метод не возвращает значение напрямую. Обработчик сообщает о доставке результата запросившему устройству и не запускает новый поиск iPhone.
Примеры использования
Обрабатывайте поступающие от устройства запросы запуска и остановки. Когда пользователь подтвердит, что iPhone найден, сначала остановите сигнал на телефоне, а затем сообщите результат устройству.
- Swift
- Objective-C
import AIBuds
final class FindPhoneCoordinator: NSObject, DeviceDelegate {
private weak var requestingDevice: DeviceConvertible?
func deviceDidRequestStartFindingPhone(_ device: DeviceConvertible) {
requestingDevice = device
DispatchQueue.main.async {
self.startPhoneAlert()
}
}
func deviceDidRequestStopFindingPhone(_ device: DeviceConvertible) {
DispatchQueue.main.async {
self.stopPhoneAlert()
}
}
func userConfirmedPhoneFound() {
stopPhoneAlert()
guard let reporter = requestingDevice as? FindPhoneStateReportingAPI else {
print("Device cannot receive a phone-found report")
return
}
reporter.notifyPhoneFound { success, error in
guard success else {
print(
"Failed to report phone found: \(error?.localizedDescription ?? "Unknown error")"
)
return
}
print("Phone-found report accepted")
}
}
}#import <AIBuds/AIBuds-Swift.h>
#import <AIBuds/AIBuds.h>
@property(nonatomic, weak) id<AIBudsDeviceConvertible> requestingDevice;
- (void)deviceDidRequestStartFindingPhone:(id<AIBudsDeviceConvertible>)device {
self.requestingDevice = device;
dispatch_async(dispatch_get_main_queue(), ^{
[self startPhoneAlert];
});
}
- (void)deviceDidRequestStopFindingPhone:(id<AIBudsDeviceConvertible>)device {
dispatch_async(dispatch_get_main_queue(), ^{
[self stopPhoneAlert];
});
}
- (void)userConfirmedPhoneFound {
[self stopPhoneAlert];
id<AIBudsFindPhoneStateReportingAPI> reporter =
(id<AIBudsFindPhoneStateReportingAPI>)self.requestingDevice;
if (![reporter conformsToProtocol:@protocol(AIBudsFindPhoneStateReportingAPI)]) {
NSLog(@"Device cannot receive a phone-found report");
return;
}
[reporter notifyPhoneFoundWithCompletion:^(BOOL success, NSError *_Nullable error) {
if (!success) {
NSLog(@"Failed to report phone found: %@",
error.localizedDescription ?: @"Unknown error");
return;
}
NSLog(@"Phone-found report accepted");
}];
}Обработка ошибок
Не связывайте состояние сигнала на iPhone с доставкой отчёта. Останавливайте сигнал сразу по запросу устройства или подтверждению пользователя, а ошибку связи notifyPhoneFound показывайте без автоматического повторного запуска сигнала.
Рекомендации
- Реагируйте на запросы устройства: запускайте индикацию на iPhone только после соответствующего вызова делегата.
- Управляйте поиском iPhone в приложении: реализуйте звук, вибрацию, разрешения, фоновое поведение и интерфейс.
- Сначала остановите сигнал: освободите локальные ресурсы оповещения до вызова
notifyPhoneFound(_:). - Сохраняйте запросившее устройство: отправляйте отчёт тому же подключённому устройству, которое запустило поиск.
- Обновляйте UI в главной очереди: направляйте работу UIKit из делегатов и обработчиков в главную очередь.
Примечания
notifyPhoneFound(_:)подтверждает завершение и не запускает поиск iPhone.- При запросе остановки от устройства приложение должно прекратить индикацию на iPhone. Это отдельное событие, не равное подтверждению пользователя о найденном телефоне.
- Если приложение должно запустить индикацию на самом подключённом устройстве, используйте
DeviceFindAPI.