Skip to content

Core Basic Features Unpair Device

Mr.P edited this page Aug 25, 2026 · 2 revisions

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

API Reference

Framework

AIBuds.xcframework

Import

Import the main header in files using the SDK:

Swift

import AIBuds

Objective-C

#import <AIBuds/AIBuds.h>
#import <AIBuds/AIBuds-Swift.h>

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

Objective-C

/// Defines common device operations including unpairing
@protocol AIBudsDeviceCommonAPI <AIBudsDeviceAPI>
    /// 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
    - (void)unpairWithCompletion:(AIBudsCompletionHandler)completion;
@end

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

Objective-C

/// 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
- (void)unpairWithCompletion:(AIBudsCompletionHandler)completion;

Parameters

Parameter Type Description
completion AIBudsCompletionHandler? An optional completion callback called when the operation completes

Callback Parameters:

Name Type Description
success Bool true if the operation succeeds, false otherwise
error NSError? 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")
        }
    }
}

Objective-C

#import <AIBuds/AIBuds.h>

@interface DeviceManager ()

/// Connected device
@property (weak, nonatomic) id<AIBudsDeviceConvertible> device;

@end

@implementation DeviceManager

- (void)unpairDevice {
    __weak typeof(self) weakSelf = self;

    id<AIBudsDeviceCommonAPI> device = (id<AIBudsDeviceCommonAPI>)self.device;
    // Check if the device supports the unpair protocol
    if ([device conformsToProtocol:@protocol(AIBudsDeviceCommonAPI)]) {
        // Execute unpair with completion handler
        [device unpairWithCompletion:^(BOOL success, NSError * _Nullable error) {
            // Handle failure case
            if (!success) {
                NSLog(@"Unpair failed: %@", error);
                return;
            }
            // Handle success case
            NSLog(@"Unpair completed successfully");
        }];
    }
}

@end

Error Handling

The completion handler may return the following error types:

Error Domain: AIBudsSDK.ErrorDomain

Swift

Error Code Description Recovery Suggestion
.deviceNotConnected Device is not connected Ensure device is paired and connected
.bleCommandExecFailedDueToTimeout Operation timed out Retry the operation
.deviceBusy Device is busy with another operation Wait for ongoing operations to complete
.deviceNotSupport Unpair is not supported on this device Check device capabilities before calling

Objective-C

Error Code Description Recovery Suggestion
AIBudsSdkErrorCodeDeviceNotConnected Device is not connected Ensure device is paired and connected
AIBudsSdkErrorCodeBleCommandExecFailedDueToTimeout Operation timed out Retry the operation
AIBudsSdkErrorCodeDeviceBusy Device is busy with another operation Wait for ongoing operations to complete
AIBudsSdkErrorCodeDeviceNotSupport Unpair is not supported on this device Check 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)
    }
}

Objective-C

/// Prompt user to unpair from iOS Settings
- (void)promptUserToUnpairFromSettings {
    UIAlertController *alert = [UIAlertController
        alertControllerWithTitle:@"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:UIAlertControllerStyleAlert];

    [alert addAction:[UIAlertAction actionWithTitle:@"Open Settings" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSURL *url = [NSURL URLWithString:@"App-prefs:Bluetooth"];
        if (url && [[UIApplication sharedApplication] canOpenURL:url]) {
            [[UIApplication sharedApplication] openURL:url options:@{} completionHandler:nil];
        }
    }]];

    [alert addAction:[UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:nil]];

    UIViewController *viewController = [UIApplication sharedApplication].windows.firstObject.rootViewController;
    [viewController presentViewController:alert animated:YES completion:nil];
}

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

AIBuds SDK iOS Wiki

Clone this wiki locally