跳到主要内容

取消配对

取消配对操作会移除设备与已连接设备之间的配对关系。当您需要永久断开设备连接或准备将其与其他设备配对时,此操作非常有用。

前提条件

执行取消配对前,请确保:

  • 设备已连接且处于稳定状态
  • 所有必要的数据同步已完成
  • 用户了解取消配对后设备将断开连接

使用 AI 辅助实现

使用 AI 开发

让 AI 帮助实现此工作流

使用官方“实现 AIBuds 设备取消配对”技能,根据你的 App 完成实现。

请阅读并遵循 https://docs-aibuds.github.io/zh-Hans/skills/implement-aibuds-unpair-device,使用该技能在当前 iOS 项目中完成“实现 AIBuds 设备取消配对”,并验证结果。
查看官方技能

API 参考

框架

AIBuds.xcframework

导入

在要使用 SDK 的文件中,导入主头文件:

Swift
import AIBuds

协议

unpair 方法定义在以下协议中。该协议继承自基础设备 API 协议。

Swift
/// Defines common device operations including unpairing
protocol DeviceCommonAPI: DeviceAPI {
    /// Unpairs the device
    /// - Parameters:
    ///   - completion: A completion callback that returns the operation result
    ///     - success: `true` if the operation succeeds, `false` otherwise
    ///     - error: An `NSError` object describing the error that occurred, or `nil` if the operation succeeds
    func unpair(_ completion: AIBudsCompletionHandler?)
}

实例方法

取消设备与已连接设备的配对。

iOS 13.0+

Swift
/// Unpairs the device
/// - Parameters:
///   - completion: A completion callback that returns the operation result
///     - success: `true` if the operation succeeds, `false` otherwise
///     - error: An `NSError` object describing the error that occurred, or `nil` if the operation succeeds
func unpair(_ completion: AIBudsCompletionHandler?)

参数

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

回调参数:

名称类型描述
successBool操作成功返回 true,否则返回 false
errorNSError?如果操作失败则包含错误信息,否则为 nil

返回值

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

使用示例

Swift
import AIBuds

class DeviceManager {

    /// Connected device
    weak var device: DeviceConvertible?

    /// Unpairs the connected device
    func unpairDevice() {
        // Check if the device supports the unpair protocol
        guard let device = device as? DeviceCommonAPI else {
            print("Device does not support unpairing")
            return
        }

        // Execute unpair with completion handler
        device.unpair { [weak self] success, error in
            // Handle failure case
            if !success {
                let errorMessage = {
                    if let error = error {
                        return "\(error)"
                    }
                    return "Unknown error"
                }()
                print("Unpair failed: \(errorMessage)")
                return
            }
            // Handle success case
            print("Unpair completed successfully")
        }
    }
}

错误处理

完成回调可能返回以下错误类型:

错误域: AIBudsSDK.ErrorDomain

错误代码描述恢复建议
.deviceNotConnected设备未连接确保设备已配对并连接
.bleCommandExecFailedDueToTimeout操作超时重试操作
.deviceBusy设备正忙于另一操作等待正在进行的操作完成
.deviceNotSupport此设备不支持取消配对调用前检查设备功能

最佳实践

  1. 向用户确认:在启动取消配对之前,始终显示确认对话框,因为此操作将断开设备连接并需要重新配对。

  2. 切换到主线程更新 UI:在完成回调中使用 DispatchQueue.main.async 更新界面。

  3. 弱引用 self:在完成回调中使用 [weak self],避免循环引用。

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

  5. 处理断开连接:成功取消配对后,优雅地处理设备断开连接并提供重新配对的指导。

平台限制

iOS 系统蓝牙限制

在 iOS 上,系统蓝牙设置不允许应用程序以编程方式取消配对蓝牙设备。这是 Apple 出于安全性和用户控制原因设置的系统级限制。

这意味着:

  • 调用 unpair 后,iOS 仍会保留设备的 BLE 配对信息
  • 设备可能会在应用重启或蓝牙开启时自动重连
  • 设备仍会在 iOS 设置 > 蓝牙中可见

推荐的用户指导:

在 iOS 应用中实现取消配对功能时,您应该引导用户手动从 iOS 设置中取消配对:

  1. 完全取消配对:引导用户前往设置 > 蓝牙,找到设备,点击 "i" 图标,然后选择 "忽略此设备"
  2. 提供清晰的 UI 反馈:当用户请求取消配对时,显示说明或深度链接到蓝牙设置
  3. 应用级别断开连接unpair 方法仍会断开设备与您应用的连接,但系统配对关系仍然保留
Swift
/// Prompt user to unpair from iOS Settings
func promptUserToUnpairFromSettings() {
    // Show alert with instructions
    let alert = UIAlertController(
        title: "Unpair Device",
        message:
            "To completely unpair the device, go to Settings > Bluetooth, find your device, tap the 'i' icon next to it, then select 'Forget This Device'.",
        preferredStyle: .alert
    )
    alert.addAction(
        UIAlertAction(title: "Open Settings", style: .default) { _ in
            // Deep link to Bluetooth settings
            if let url = URL(string: "App-prefs:Bluetooth") {
                UIApplication.shared.open(url)
            }
        })
    alert.addAction(UIAlertAction(title: "Cancel", style: .cancel))

    // Present alert
    if let viewController = UIApplication.shared.windows.first?.rootViewController {
        viewController.present(alert, animated: true)
    }
}

注意事项

  • 取消配对命令执行后,设备将断开连接
  • 设备需要重新配对才能再次连接
  • 所有配对信息将从两个设备中删除
  • 任何正在进行的操作将被中断
  • 取消配对可能需要几秒钟完成