Skip to main content

Unpair Device

The unpair device operation removes the pairing relationship between the device and the connected device. This operation is useful when you need to disconnect the device permanently or prepare it for pairing with another device.

Prerequisites

Before performing unpairing, ensure the following:

  • The device is connected and in a stable state
  • All necessary data synchronization is complete
  • The user understands that the device will be disconnected after unpairing

Implement with AI Assistance

Build with AI

Implement this workflow with AI

Use the official Implement AIBuds Device Unpairing skill to adapt this workflow to your app.

Read and follow https://docs-aibuds.github.io/skills/implement-aibuds-unpair-device. Use it to implement Implement AIBuds Device Unpairing in this iOS project and verify the result.
View official skill

API Reference

Framework

AIBuds.xcframework

Import

Import the main header in files using the SDK:

Swift
import AIBuds

Protocol

The unpair method is defined in the following protocol, which inherits from the basic device API protocol.

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?)
}

Instance Method

Unpairs the device from the connected device.

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?)

Parameters

ParameterTypeDescription
completionAIBudsCompletionHandler?An optional completion callback called when the operation completes

Callback Parameters:

NameTypeDescription
successBooltrue if the operation succeeds, false otherwise
errorNSError?Contains error information if the operation fails, nil otherwise

Return Value

This method does not return a value directly. Results are provided through the completion callback.

Usage Examples

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")
        }
    }
}

Error Handling

The completion handler may return the following error types:

Error Domain: AIBudsSDK.ErrorDomain

Error CodeDescriptionRecovery Suggestion
.deviceNotConnectedDevice is not connectedEnsure device is paired and connected
.bleCommandExecFailedDueToTimeoutOperation timed outRetry the operation
.deviceBusyDevice is busy with another operationWait for ongoing operations to complete
.deviceNotSupportUnpair is not supported on this deviceCheck device capabilities before calling

Best Practices

  1. User Confirmation: Always display a confirmation dialog before initiating unpairing. This action disconnects the device and requires re-pairing.

  2. Background Execution Handling: Wrap the completion handler in a DispatchQueue.main.async block when updating UI.

  3. Weak Self Reference: Use [weak self] in the completion handler to prevent retain cycles.

  4. Protocol Conformance Check: Verify that the device conforms to the DeviceCommonAPI protocol before calling the method.

  5. Disconnection Handling: After successful unpairing, properly handle device disconnection and provide guidance for reconnection.

Platform Limitations

iOS System Bluetooth Limitation

On iOS, applications cannot programmatically unpair Bluetooth devices from the system Bluetooth settings. This is a system-level restriction set by Apple for security and user control.

Implications:

  • iOS continues to maintain BLE pairing information for the device even after calling unpair
  • The device may automatically reconnect when the app restarts or Bluetooth is enabled
  • The device continues to appear in iOS Settings > Bluetooth

Recommended User Guidance:

When implementing unpair functionality in an iOS app, you should guide users to manually unpair in iOS Settings:

  1. Complete Unpairing: Instruct users to go to "Settings > Bluetooth", find the device, tap the "i" icon, then select "Forget This Device"
  2. Provide Clear UI Feedback: When a user requests unpairing, display instructions or a deep link to Bluetooth settings
  3. App-level Disconnection: The unpair method still disconnects from the device, but system pairing remains intact
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)
    }
}

Notes

  • The device will be disconnected after the unpair command is executed
  • Re-pairing is required to connect the device again
  • All pairing information is removed from both devices
  • All ongoing operations will be interrupted
  • Unpair may take a few seconds to complete