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

Фотосъёмка

Запустите сеанс фотосъёмки устройства с CaptureMode, затем остановите его в нужный момент.

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

  • Устройство подключено и поддерживает DeviceCameraAPI. Устройства без встроенного хранилища могут передавать снятый JPEG напрямую приложению.

Справочник API​

Протокол​

Swift
/// The protocol for device API that supports camera.
protocol DeviceCameraAPI: DeviceAPI {
    /// Requests to take a photo with the specified capture mode.
    /// - Parameters:
    ///   - mode: The capture mode for photo taking.
    ///   - completion: A closure that is called when the operation completes.
    ///     - success: `true` if the operation was successful; otherwise `false`.
    ///     - statusCode: The status code returned by the device. `nil` if the operation failed.
    ///     - error: An `NSError` object that describes the error that occurred, or `nil` if the operation was successful.
    func requestPhotoTaking(
        withCaptureMode mode: CaptureMode,
        completion: AIBudsStatusCodeCompletionHandler?
    )

    /// Requests to stop the current photo taking session.
    /// - Parameters:
    ///   - completion: A closure that is called when the operation completes.
    ///     - success: `true` if the operation was successful; otherwise `false`.
    ///     - statusCode: The status code returned by the device. `nil` if the operation failed.
    ///     - error: An `NSError` object that describes the error that occurred, or `nil` if the operation was successful.
    func requestStopPhotoTaking(_ completion: AIBudsStatusCodeCompletionHandler?)
}
МетодНазначение
requestPhotoTakingЗапустить фотосъёмку в режиме .camera или .ai.
requestStopPhotoTakingОстановить активный сеанс фотосъёмки.

Обработчики запроса возвращают success, необязательный statusCode устройства и необязательный NSError, но не путь к файлу снимка.

Обработчик мгновенного снимка​

Очки без хранилища передают снятый JPEG через необязательный обработчик device(_:didReceiveInstantPhotoData:error:). Реализуйте его в DeviceDelegate или SDKDelegate, сначала обработайте error, а отсутствие или пустое значение photoData считайте неудачной передачей.

Swift
func device(
    _ device: DeviceConvertible,
    didReceiveInstantPhotoData photoData: Data?,
    error: NSError?
) {
    guard error == nil, let photoData, !photoData.isEmpty else { return }
    // Decode or persist the JPEG away from the callback path.
}

SDK вызывает этот обработчик после съёмки на поддерживаемых очках без хранилища. Не ожидайте его на устройствах, сохраняющих фотографии во встроенное хранилище, а работу с интерфейсом или медиатекой выполняйте в подходящей очереди.

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

Swift
guard let device = device as? DeviceCameraAPI else { return }

device.requestPhotoTaking(withCaptureMode: .camera) { success, statusCode, error in
    guard success else {
        print(error?.localizedDescription ?? "Photo request failed")
        return
    }
    print("Photo taking started: \(statusCode?.stringValue ?? "Unavailable")")
}

device.requestStopPhotoTaking { success, _, error in
    if !success { print(error?.localizedDescription ?? "Stop failed") }
}