[swift] Swift Core Bluetooth와 외부 장치와의 연결

Swift Core Bluetooth는 iOS와 macOS에서 BLE (Bluetooth Low Energy) 장치와 통신하기 위한 프레임워크입니다. 이를 사용하여 iOS와 macOS 애플리케이션과 외부 BLE 장치를 연결하고 데이터를 주고받을 수 있습니다.

이번 글에서는 Swift Core Bluetooth를 사용하여 외부 장치와의 연결 과정을 살펴보겠습니다.

1. CBCentralManager 객체 생성

Core Bluetooth를 사용하기 위해 먼저 CBCentralManager 객체를 생성해야 합니다. 이 객체는 BLE 장치와의 연결 및 통신을 관리하는 역할을 합니다. 객체를 생성할 때엔 CBCentralManagerDelegate 프로토콜을 준수해야 합니다.

import CoreBluetooth

class ViewController: UIViewController, CBCentralManagerDelegate {
    var centralManager: CBCentralManager!
    
    override func viewDidLoad() {
        super.viewDidLoad()

        centralManager = CBCentralManager(delegate: self, queue: nil)
    }
}

2. 중앙 장치의 상태 확인

CBCentralManagerDelegate 프로토콜을 준수하는 경우, 중앙 장치의 상태 변화를 감지할 수 있습니다. 연결 가능한 상태인지 확인하기 위해 centralManagerDidUpdateState 메서드를 구현해야 합니다.

func centralManagerDidUpdateState(_ central: CBCentralManager) {
    switch central.state {
    case .poweredOn:
        print("Bluetooth is powered on.")
    case .poweredOff:
        print("Bluetooth is powered off.")
    case .resetting:
        print("Bluetooth is resetting.")
    case .unauthorized:
        print("Bluetooth is unauthorized.")
    case .unknown:
        print("Bluetooth state is unknown.")
    case .unsupported:
        print("Bluetooth is unsupported.")
    @unknown default:
        fatalError()
    }
}

3. 외부 장치 검색

중앙 장치의 상태가 “powered on”인 경우, 외부 BLE 장치를 검색할 수 있습니다. 이를 위해 scanForPeripherals 메서드를 사용합니다.

func centralManagerDidUpdateState(_ central: CBCentralManager) {
    if central.state == .poweredOn {
        centralManager.scanForPeripherals(withServices: nil, options: nil)
    }
}

func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
    // 외부 장치를 발견했을 때의 동작을 구현합니다.
    print("Peripheral discovered: \(peripheral)")
}

4. 외부 장치 연결

외부 장치를 검색한 후에는 해당 장치와 연결할 수 있습니다. 이를 위해 connect 메서드를 사용합니다.

func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
    // 외부 장치를 발견했을 때의 동작을 구현합니다.
    print("Peripheral discovered: \(peripheral)")

    // 외부 장치와의 연결을 시도합니다.
    centralManager.connect(peripheral, options: nil)
}

func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
    // 외부 장치와의 연결이 성공했을 때의 동작을 구현합니다.
    print("Peripheral connected: \(peripheral)")
}

위와 같이 Swift Core Bluetooth를 사용하여 외부 장치와의 연결을 수행할 수 있습니다. 연결된 후에는 데이터를 읽거나 쓸 수 있으며, CBPeripheralDelegate 프로토콜을 통해 관련 이벤트를 제어할 수도 있습니다.

더 자세한 내용은 Apple 개발자 문서를 참조하세요.