跳到主要内容

查询媒体数量

向已连接设备请求最新的照片、视频和音频文件数量,然后读取更新后的 mediaCountInfo 属性。

前置条件

查询媒体数量前,请确保:

  • 设备已连接并处于稳定状态。
  • 设备支持 DeviceInfoAPI 协议。

API 参考

框架

AIBuds.xcframework

导入

在需要使用 SDK 的文件中导入主框架:

Swift
import AIBuds

协议

请求方法和结果属性定义在 DeviceInfoAPI 中。

Swift
protocol DeviceInfoAPI: DeviceAPI {
    /// Media file count information, including counts for photos, videos,
    /// audio, etc.
    var mediaCountInfo: MediaCountInfoModel? { get }

    /// Request to query the device media count information.
    /// - Parameters:
    ///   - 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 requestQueryMediaCountInfo(
        _ completion: AIBudsCompletionHandler?
    )
}

实例方法

请求设备中存储媒体的最新数量。

Swift
/// Request to query the device media count information.
/// - Parameters:
///   - 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 requestQueryMediaCountInfo(
    _ completion: AIBudsCompletionHandler?
)

参数

参数类型描述
completionAIBudsCompletionHandler?请求结束时调用的可选完成回调。

回调参数:

名称类型描述
successBool / BOOL请求成功时为 true,否则为 false
errorNSError?请求失败时的错误详情;成功时为 nil

结果属性:

属性类型描述
photoCountNSNumber照片数量。
videoCountNSNumber视频数量。
audioCountNSNumber音频文件数量。

返回值

该方法不会在完成回调中返回媒体数量。请求成功后,请读取更新后的 mediaCountInfo 属性。

使用示例

Swift
import AIBuds

final class DeviceManager {
    weak var device: DeviceConvertible?

    func queryMediaCount() {
        guard let device = device as? DeviceInfoAPI else {
            print("Device does not support media-count queries")
            return
        }

        device.requestQueryMediaCountInfo { success, error in
            guard success else {
                print("Media-count query failed: \(error?.localizedDescription ?? "Unknown error")")
                return
            }

            guard let counts = device.mediaCountInfo else {
                print("The device did not provide media-count information")
                return
            }

            print("Photos: \(counts.photoCount)")
            print("Videos: \(counts.videoCount)")
            print("Audio files: \(counts.audioCount)")
        }
    }
}

错误处理

  1. 读取刷新后的属性前,先检查 success
  2. 请求失败时,通过 error 获取失败详情。
  3. 即使回调成功,也要处理返回 nilmediaCountInfo
  4. 除非目标设备文档明确说明,否则不要假设固定错误码。

最佳实践

  1. 成功后读取:仅在查询成功完成后访问 mediaCountInfo
  2. 使用公开字段:分别读取照片、视频和音频数量。
  3. 检查协议支持:确认设备支持 DeviceInfoAPI
  4. 在主队列更新 UI:将完成回调触发的 UIKit 更新派发到主队列。

注意事项

  • 完成回调仅报告请求状态,不包含 MediaCountInfoModel 结果。
  • MediaCountInfoModelNSNumber 值提供照片、视频和音频数量。
  • SDK 未在该模型中提供 totalCount 属性。
  • 拍摄、导入或删除文件时,媒体数量可能发生变化。