[ios] Core Bluetooth 기기 탐색

Core Bluetooth를 사용하면 iOS 앱에서 주변 기기를 탐색하고 연결할 수 있습니다. 이 기능을 사용하려면 몇 가지 단계를 따라야 합니다.

1. Bluetooth 권한 요청

앱에서 Bluetooth를 사용하려면 Info.plist 파일에 NSBluetoothAlwaysUsageDescription 또는 NSBluetoothPeripheralUsageDescription 키를 추가하여 Bluetooth 권한을 요청해야 합니다. 권한이 허용되어야만 기기를 탐색하고 연결할 수 있습니다.

2. CBCentralManager 설정

CBCentralManager 인스턴스를 생성하여 Bluetooth 기기를 탐색할 수 있습니다. 다음은 CBCentralManager를 생성하는 예시 코드입니다.

import CoreBluetooth

var centralManager: CBCentralManager!

override func viewDidLoad() {
    super.viewDidLoad()
    centralManager = CBCentralManager(delegate: self, queue: nil)
}

3. 기기 탐색

CBCentralManagerDelegate를 채택하여 centralManagerDidUpdateState 메서드를 구현하고, Bluetooth 상태가 powered on인지 확인합니다. 그런 다음 scanForPeripherals 메서드를 사용하여 주변에 있는 Bluetooth 기기를 탐색합니다.

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

4. 기기 발견 처리

기기가 발견되면 didDiscover 델리게이트 메서드가 호출됩니다. 해당 메서드에서 기기를 연결하거나 원하는 동작을 수행할 수 있습니다.

func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
    // 기기 발견 시 동작 수행
}

요약

위에서 설명한 단계를 따라 앱에서 Core Bluetooth를 사용하여 기기를 탐색할 수 있습니다. 각 단계에서 UI 및 다양한 오류 처리 등 고려해야 할 사항이 있으므로 주의가 필요합니다.

자세한 내용은 Apple의 Core Bluetooth 가이드를 참조할 수 있습니다.