# Bluetooth Permission Prompt Automation on macOS

Canonical: https://figment.so/blog/mac-bluetooth-permission-prompt-uitest

Run this CoreBluetooth permission test on a physical Mac you control. No Figment plan has a Bluetooth radio available to the test, so a hosted Mac cannot reach allowedAlways.

**Run this test on a physical Mac you control, because CoreBluetooth needs a real radio and a real TCC (privacy permission) database.** No Figment plan has a Bluetooth radio available to guest software, so `CBCentralManager` will not reach `allowedAlways` on a Figment Mac or VM, and we have not measured Bluetooth on any plan. The code below is still useful on a hosted Mac for build and unit-test work. API references: [CBCentralManager](https://developer.apple.com/documentation/corebluetooth/cbcentralmanager) and [NSBluetoothAlwaysUsageDescription](https://developer.apple.com/documentation/bundleresources/information_property_list/nsbluetoothalwaysusagedescription).

## When does macOS show the Bluetooth prompt?

It shows the "Allow [App] to use Bluetooth?" alert the first time your app instantiates `CBCentralManager(delegate:queue:)`. The prompt does not fire at import or at launch. The initializer fires it, and only if `NSBluetoothAlwaysUsageDescription` is in the app target's `Info.plist`. Without the key the system suppresses the dialog and the manager stays unauthorized.

```xml
<key>NSBluetoothAlwaysUsageDescription</key>
<string>MyApp needs Bluetooth to discover your peripheral device.</string>
```

The string is the text the user reads. Keep it concrete, because a vague "for a better experience" string confuses both testers and App Review.

## How do I wait for the delegate without flaky tests?

Use `XCTNSPredicateExpectation`, which polls until the predicate is true or a timeout fires. `CBCentralManager` reports its state asynchronously: after `init`, `centralManagerDidUpdateState(_:)` fires on the designated queue once the manager has consulted TCC. Asserting `CBCentralManager.authorization == .allowedAlways` right after `init` almost always fails, because the value is `.notDetermined` at that instant.

```swift
let authPredicate = NSPredicate { _, _ in
    CBCentralManager.authorization == .allowedAlways
}
let authExpectation = XCTNSPredicateExpectation(
    predicate: authPredicate,
    object: nil
)
let result = XCTWaiter().wait(for: [authExpectation], timeout: 10)
XCTAssertEqual(result, .completed, "Timed out waiting for Bluetooth authorization")
```

Ten seconds is a comfortable starting point. Measure your own machine before tightening it, because CI hosts under load can be noticeably slower than a developer laptop.

## How do I tap Allow on the macOS Bluetooth alert?

Register an interruption monitor before you create the manager, and fall back to querying the alert through the app's windows if the monitor does not fire. On macOS the consent dialog is a separate window owned by the user session, not an in-app alert. `addUIInterruptionMonitor` is documented mainly for iOS XCUITest, so verify in your installed Xcode that the monitor fires for the consent window on your target OS version. If it does not, tap Allow by label through the app's windows.

```swift
let allowed = addUIInterruptionMonitor(withDescription: "Bluetooth permission") { alert in
    let allowButton = alert.buttons["Allow"]
    guard allowButton.waitForExistence(timeout: 2) else { return false }
    allowButton.tap()
    return true
}
defer { removeUIInterruptionMonitor(allowed) }

// This call triggers the alert on first run after a TCC reset.
let manager = CBCentralManager(delegate: delegate, queue: .main)

// XCTest only drains interruption monitors when there is a pending UI interaction.
app.activate()
app.tap()
```

If permission was already granted in an earlier run and no alert appears, the monitor never fires. That is not a failure.

## How do I assert allowedAlways?

Once the predicate completes, assert the state through the class property on `CBCentralManager`. The [CBCentralManager reference](https://developer.apple.com/documentation/corebluetooth/cbcentralmanager) has the availability row for your deployment target.

```swift
XCTAssertEqual(
    CBCentralManager.authorization,
    .allowedAlways,
    "Manager should be allowedAlways after the user tapped Allow"
)
```

## How do I reset the Bluetooth permission between runs?

Run `tccutil reset` in `setUpWithError()`. Without a reset, the second run finds the permission already granted and never sees the alert, so the alert path goes untested.

```swift
override func setUpWithError() throws {
    let proc = Process()
    proc.executableURL = URL(fileURLWithPath: "/usr/bin/tccutil")
    proc.arguments = ["reset", "Bluetooth", "com.example.MyApp"]
    try proc.run()
    proc.waitUntilExit()
    guard proc.terminationStatus == 0 else {
        throw XCTSkip("tccutil reset failed; check the bundle ID")
    }
}
```

`tccutil reset Bluetooth <bundleID>` removes only that app's Bluetooth entry and does not require SIP to be disabled. If you omit the bundle ID, `tccutil` resets all Bluetooth entries on the machine. That is fine on a dedicated CI Mac and less fine on a shared one.

## How do I export the final authorization as evidence?

Attach a timestamped JSON record to the test, so the result survives merging across parallel runs.

```swift
func attachAuthStatus(_ status: CBManagerAuthorization, to test: XCTestCase) {
    let stateNames: [CBManagerAuthorization: String] = [
        .notDetermined: "notDetermined",
        .restricted:    "restricted",
        .denied:        "denied",
        .allowedAlways: "allowedAlways",
    ]
    let payload: [String: Any] = [
        "authorization": stateNames[status] ?? "unknown(\(status.rawValue))",
        "timestamp":     ISO8601DateFormatter().string(from: Date()),
        "bundleID":      Bundle.main.bundleIdentifier ?? "unset",
    ]
    guard let data = try? JSONSerialization.data(
        withJSONObject: payload,
        options: .prettyPrinted
    ) else { return }

    let attachment = XCTAttachment(
        data: data,
        uniformTypeIdentifier: "public.json"
    )
    attachment.name = "bluetooth-auth-status.json"
    attachment.lifetime = .keepAlways
    test.add(attachment)
}
```

Call `attachAuthStatus(CBCentralManager.authorization, to: self)` at the end of the test. The file lands inside the `.xcresult` bundle under **Attachments** in Xcode's Test navigator and exports as plain JSON.

## Which host can run this test?

A Mac with a Bluetooth radio that you can sit at or control physically. Other hosted Macs may differ, so ask the provider whether the guest sees a Bluetooth controller before you pay. The listed prices below are for context and are not equal hardware.

| Host | Listed price | Bluetooth for this test |
|------|--------------|-------------------------|
| Physical Mac you control | Hardware you own | Yes, if the Mac has a radio |
| Figment plans (Intel VM, Apple Silicon VM, Dedicated M4 Pro) | $25, $39 and $349 a month | Not available or not measured |
| [CloudMac M4 / 16 GB / 256 GB](https://cloudmac.org/pricing) | $99.99/month, or [$999/year](https://cloudmac.org/) ($83.25 effective/month) | Ask the provider |
| [MacStadium M4.S (16 GB / 256 GB)](https://macstadium.com/pricing) | $149/month | Ask the provider |

Arithmetic: $999 ÷ 12 = $83.25. CloudMac's 512 GB and 1 TB rows were listed as fully reserved and the 256 GB row showed Reserve now. MacStadium's catalog includes support and a published 99.99% uptime claim, with multi-year terms via sales.

## Can any Figment Mac test the Bluetooth permission prompt?

None of them for the Bluetooth prompt itself. Use a Figment Mac for the rest of the pipeline: building the app, running unit tests and running the test target's other UI tests. The Intel Mac VM ($25 a month) covers Xcode 26.3 or earlier on macOS Sequoia, and the Apple Silicon Mac VM ($39 a month) covers current Xcode. Compare the [Mac hosting plans](/mac-hosting) and check the versions shown before purchase.

**Related guides:**
- [macOS WCAG 2.2 Safari Audit Checklist](/blog/mac-wcag22-safari-audit-checklist)
- [iOS Simulator Parallel Device Matrix](/blog/mac-simulator-parallel-device-matrix)
- [Self-Hosted GitHub Actions Runner on Mac](/blog/mac-github-actions-self-hosted-runner)
