Dunfey · Hotel WWDC as data, est. 1983
Front desk everything
Years
Topics

2021 Health & FitnessSystem Services

WWDC21 · 11 min · Health & Fitness / System Services

Connect Bluetooth devices to Apple Watch

Discover how you can integrate data from Bluetooth accessories into Apple Watch apps and complications. Bluetooth devices can provide medical data, sports stats, and more to Apple Watch, and help people get more out of your software in the process. We’ll show you how to connect to these devices during Background App Refresh to display the most up-to-date information in your Apple Watch complications, provide an overview of Core Bluetooth on watchOS, and explore best practices for Bluetooth accessory design.

Watch at developer.apple.com ↗

Transcript all transcripts

Code shown on screen · 4 snippets

didDiscoverPeripheral swift · at 7:35 ↗
func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String: Any], rssi RSSI: NSNumber ) {

    // Add to an array of discovered peripherals,
    // then connect to the peripheral.

    central.connect(peripheral, options: nil)

}
handleBackgroundTasks swift · at 7:55 ↗
func handle(_ backgroundTasks: Set<WKRefreshBackgroundTask>) {
    for task in backgroundTasks {
        if let refreshTask = task as? WKApplicationRefreshBackgroundTask {
            // Insert your code to start background work here.
            central.connect(peripheral, options: nil)
            refreshTask.expirationHandler = {
                // Insert your code to cancel existing work here.
                if let peripheral = self.bluetoothReceiver.connectedPeripheral {
                    self.central.cancelPeripheralConnection(peripheral)
                }
                refreshTask.setTaskCompletedWithSnapshot(false)
            }
        }
    }
}
didDisconnectPeripheral swift · at 8:51 ↗
// If the app gets woken up to handle a background refresh task, this method will be called
// if a peripheral was disconnected when the app had previously transitioned to the
// background.
func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) {
    connectedPeripheral = nil
    delegate?.didCompleteDisconnection(from: peripheral)
}
didCompleteDisconnection swift · at 9:08 ↗
// In your WatchKit Extension delegate:

func didCompleteDisconnection(from peripheral: CBPeripheral) {
    if let refreshTask = currentRefreshTask {
        task.setTaskCompletedWithSnapshot(false)
        currentRefreshTask = nil
    }
}

Resources