[swift] Swift Core Bluetooth 디바이스 검색 및 스캔

Swift Core Bluetooth는 iOS 기기에서 블루투스 기능을 사용하여 주변 디바이스와 상호 작용하기 위한 프레임워크입니다. 이를 사용하여 디바이스를 검색하고 스캔하는 방법을 알아보겠습니다.

1. CBCentralManager 인스턴스 생성

CBCentralManager 클래스의 인스턴스를 생성하여 블루투스 관리자를 초기화합니다. 이 관리자를 사용하여 디바이스 검색 및 연결 등의 작업을 수행할 수 있습니다.

import CoreBluetooth

// 블루투스 관리자 인스턴스 생성
let centralManager = CBCentralManager(delegate: self, queue: nil)

2. 블루투스 상태 확인

블루투스 상태를 확인하기 위해 CBCentralManagerDelegate 프로토콜을 준수해야 합니다. centralManagerDidUpdateState 메서드를 구현하여 현재 블루투스 상태를 확인하고 연결할 수 있는 상태인지 확인합니다.

extension ViewController: CBCentralManagerDelegate {
    func centralManagerDidUpdateState(_ central: CBCentralManager) {
        switch central.state {
        case .poweredOn:
            print("Bluetooth is powered on and available.")
            // 디바이스 스캔 시작
            centralManager.scanForPeripherals(withServices: nil, options: nil)
        case .poweredOff:
            print("Bluetooth is powered off.")
        case .unauthorized:
            print("Bluetooth authorization denied.")
        case .unknown:
            print("Bluetooth state is unknown.")
        case .unsupported:
            print("Bluetooth is not supported on this device.")
        case .resetting:
            print("Bluetooth is resetting.")
        default:
            print("Unknown Bluetooth state.")
        }
    }
}

3. 디바이스 검색 및 스캔

scanForPeripherals(withServices:options:) 메서드를 사용하여 디바이스를 검색하고 스캔할 수 있습니다. 필요한 경우 CBUUID 객체를 사용하여 특정 서비스를 가진 디바이스만 검색할 수도 있습니다.

// 디바이스 검색 시작
centralManager.scanForPeripherals(withServices: nil, options: nil)

스캔된 디바이스 목록은 centralManager(_:didDiscover:advertisementData:rssi:) 메서드를 통해 확인할 수 있습니다. 이 메서드를 구현하여 스캔된 디바이스 정보를 받아올 수 있습니다.

extension ViewController: CBCentralManagerDelegate {
    func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
        print("Discovered peripheral: \(peripheral.name ?? "")")
        // 발견된 디바이스에 대한 추가 작업 수행
    }
}

위의 코드에서는 peripheral.name을 통해 디바이스의 이름을 확인할 수 있습니다. 다른 디바이스 정보도 advertisementData를 통해 확인할 수 있습니다.

결론

Swift Core Bluetooth를 사용하여 iOS 앱에서 디바이스를 검색하고 스캔하는 방법을 알아보았습니다. CBCentralManager 클래스를 사용하여 블루투스 관리자 인스턴스를 생성하고, CBCentralManagerDelegate 프로토콜을 준수하여 블루투스 상태를 확인하고 디바이스를 검색할 수 있습니다. 이를 바탕으로 블루투스 기능을 활용한 다양한 기능을 개발할 수 있습니다.

관련 문서: