跳到主要内容

同步设备时间

将连接设备的内部时钟与当前时间同步。当设备只需校准时钟而无需指定具体日期时,使用此操作。

前置条件

同步设备时间前,请确保:

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

API 参考

框架

AIBuds.xcframework

导入

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

Swift
import AIBuds

协议

syncDeviceTime 方法定义在 DeviceInfoAPI 中,该协议继承自基础设备 API 协议。

Swift
/// The protocol for device information related API.
protocol DeviceInfoAPI: DeviceAPI {
    /// Synchronizes the device time with the current time.
    /// - 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 syncDeviceTime(_ completion: AIBudsStatusCodeCompletionHandler?)
}

实例方法

将设备时间与当前时间同步。

Swift
/// Synchronizes the device time with the current time.
/// - 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 syncDeviceTime(_ completion: AIBudsStatusCodeCompletionHandler?)

参数

参数类型描述
completionAIBudsStatusCodeCompletionHandler?操作结束时调用的可选完成回调。

回调参数:

名称类型描述
successBool / BOOL操作成功时为 true,否则为 false
statusCodeNSNumber?设备返回的状态码。SDK 文档规定,操作失败时该值为 nil
errorNSError?操作失败时的错误详情;成功时为 nil

返回值

该方法不直接返回值,结果通过完成回调提供。

使用示例

Swift
import AIBuds

final class DeviceManager {

    /// The connected device
    weak var device: DeviceConvertible?

    /// Synchronizes the connected device with the current time
    func synchronizeDeviceTime() {
        guard let device = device as? DeviceInfoAPI else {
            print("Device does not support time synchronization")
            return
        }

        device.syncDeviceTime { success, statusCode, error in
            if !success {
                print(
                    "Time synchronization failed: "
                        + (error?.localizedDescription ?? "Unknown error")
                )
                return
            }

            print(
                "Time synchronized successfully. Status code: " + (statusCode?.stringValue ?? "N/A")
            )
        }
    }
}

错误处理

完成回调报告同步结果:

  1. 将操作视为完成前,先检查 success
  2. successfalse 时,通过 error 获取失败详情。
  3. statusCode 可用时保留该值,用于诊断或设备特定处理。
  4. 除非目标设备文档明确说明,否则不要假设特定错误码或状态码。

最佳实践

  1. 检查协议支持:调用方法前确认设备支持 DeviceInfoAPI

  2. 连接后调用:仅在设备已连接且就绪后同步时间。

  3. 处理全部回调值:同时判断 successstatusCodeerror,不要只依赖 error

  4. 在主队列更新 UI:将完成回调触发的 UIKit 更新派发到主队列。

注意事项

  • syncDeviceTime 不接受目标 Date;需要指定时间时,请使用 setDeviceTime(to:completion:)
  • 公开 API 仅说明与当前时间同步,并未定义 UTC 转换约定。
  • 时间同步支持情况可能因设备型号和固件而异。