[ios] Core Bluetooth 데이터 교환

iOS 애플리케이션에서 Core Bluetooth 프레임워크를 사용하여 Bluetooth 기기와 데이터를 교환하는 방법을 알아봅니다.

Core Bluetooth 개요

Core Bluetooth는 iOS 기기와 Bluetooth LE(저에너지) 기기 간에 데이터를 교환하기 위한 프레임워크입니다. Bluetooth 통신을 통해 주변 장치와 상호 작용할 수 있도록 해줍니다.

Bluetooth 기기 연결

먼저 Bluetooth 기기와 iOS 기기를 연결해야 합니다. Central 및 Peripheral 역할을 할 iOS 기기와 Bluetooth 기기를 서로 연결합니다.

import CoreBluetooth

class ViewController: UIViewController, CBCentralManagerDelegate, CBPeripheralDelegate {
    var centralManager: CBCentralManager!
    var peripheralDevice: CBPeripheral!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        centralManager = CBCentralManager(delegate: self, queue: nil)
    }
    
    func centralManagerDidUpdateState(_ central: CBCentralManager) {
        if central.state == .poweredOn {
            central.scanForPeripherals(withServices: nil, options: nil)
        } else {
            // Bluetooth가 비활성 상태임을 사용자에게 알림
        }
    }
    
    func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
        if peripheral.name == "YourPeripheralName" {
            central.stopScan()
            self.peripheralDevice = peripheral
            central.connect(peripheral, options: nil)
        }
    }
    
    func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
        peripheral.delegate = self
        peripheral.discoverServices(nil)
    }
}

데이터 통신

연결이 설정되면 데이터를 교환할 수 있습니다. Peripheral에서 데이터를 읽거나 Central에서 데이터를 쓸 수 있습니다.

func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
    guard let services = peripheral.services else { return }
    for service in services {
        if service.uuid == CBUUID(string: "YourServiceUUID") {
            peripheral.discoverCharacteristics(nil, for: service)
        }
    }
}

func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
    guard let characteristics = service.characteristics else { return }
    for characteristic in characteristics {
        if characteristic.uuid == CBUUID(string: "YourCharacteristicUUID") {
            // 데이터를 읽거나 쓰는 작업 수행
            // peripheral.readValue(for: characteristic)
            // peripheral.writeValue(data, for: characteristic, type: .withResponse)
        }
    }
}

데이터 교환 완료

데이터를 교환하고 나면 연결을 종료해야 합니다.

func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
    if let data = characteristic.value {
        // 데이터를 수신한 경우
    }
}

func peripheral(_ peripheral: CBPeripheral, didWriteValueFor characteristic: CBCharacteristic, error: Error?) {
    // 데이터를 쓴 후에 수행할 작업
}

func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) {
    // 연결 종료 후의 작업 수행
}

이제 Core Bluetooth를 사용하여 iOS 애플리케이션과 Bluetooth 기기 간에 데이터를 교환하는 방법을 알게 되었습니다.

참고 문헌: