[swift] Swift Core Bluetooth와의 데이터 통신

iOS 개발을 위한 Swift 언어는 많은 기능을 제공합니다. 그 중에서도 Core Bluetooth 프레임워크는 다양한 블루투스 기능을 제어할 수 있는 기능을 제공합니다. 이를 통해 iOS 기기와 다른 블루투스 장치와의 데이터 통신을 쉽게 할 수 있습니다.

이번 글에서는 Swift Core Bluetooth를 사용하여 iOS 기기와 다른 블루투스 장치 간에 데이터를 주고받는 방법을 알아보겠습니다.

Core Bluetooth 프레임워크 가져오기

Core Bluetooth 프레임워크를 사용하기 위해서는 프로젝트에 해당 프레임워크를 추가해야 합니다. 이를 위해 Xcode에서 프로젝트를 선택하고, “General” 탭에서 “Linked Frameworks and Libraries” 섹션을 찾아 Core Bluetooth 프레임워크를 추가하십시오.

Bluetooth 연결 설정하기

Bluetooth을 사용하기 위해선 먼저 CBCentralManager를 사용하여 Bluetooth 연결을 설정해야 합니다. 이를 위해 다음과 같은 코드를 작성할 수 있습니다.

import CoreBluetooth

class ViewController: UIViewController {
    var centralManager: CBCentralManager!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        centralManager = CBCentralManager(delegate: self, queue: nil)
    }
}

extension ViewController: CBCentralManagerDelegate {
    func centralManagerDidUpdateState(_ central: CBCentralManager) {
        if central.state == .poweredOn {
            // Bluetooth가 켜진 상태일 때의 처리
        } else {
            // Bluetooth가 꺼진 상태일 때의 처리
        }
    }
}

위 코드에서 centralManagerDidUpdateState 메서드를 통해 Bluetooth의 상태를 알 수 있습니다. Bluetooth가 켜진 상태일 때는 연결할 장치를 찾는 로직을 구현할 수 있습니다.

Bluetooth 장치 검색하기

Core Bluetooth를 사용하여 검색할 Bluetooth 장치를 찾을 수 있습니다. 이를 위해서는 다음과 같은 코드를 작성하면 됩니다.

func scanForDevices() {
    centralManager.scanForPeripherals(withServices: nil, options: nil)
}

extension ViewController: CBCentralManagerDelegate {
    func centralManagerDidUpdateState(_ central: CBCentralManager) {
        if central.state == .poweredOn {
            scanForDevices()
        }
    }
    
    func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral,
                        advertisementData: [String : Any], rssi RSSI: NSNumber) {
        // 검색된 Bluetooth 장치에 대한 처리
    }
}

위 코드에서 scanForDevices 메서드를 호출하여 Bluetooth 장치를 검색할 수 있습니다. centralManager:didDiscover:advertisementData:rssi: 메서드에서는 검색된 Bluetooth 장치에 대한 처리 로직을 구현할 수 있습니다.

Bluetooth 장치와의 연결

검색된 Bluetooth 장치를 선택하여 연결할 수 있습니다. 다음과 같은 코드를 사용하면 됩니다.

func connectToDevice(device: CBPeripheral) {
    centralManager.connect(device, options: nil)
}

extension ViewController: CBCentralManagerDelegate {
    // ...
    
    func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
        // 연결에 성공한 Bluetooth 장치에 대한 처리
    }
}

위 코드에서는 connectToDevice 메서드를 호출하여 선택한 Bluetooth 장치와 연결할 수 있습니다. 연결에 성공하면 centralManager:didConnect: 메서드가 호출되며, 연결된 Bluetooth 장치에 대한 처리 로직을 구현할 수 있습니다.

데이터 통신하기

Bluetooth 장치와 연결이 이루어진 후에는 데이터를 주고 받을 수 있습니다. 다음과 같은 코드를 사용하여 데이터를 통신할 수 있습니다.

func sendDataToDevice(data: Data, device: CBPeripheral) {
    device.writeValue(data, for: characteristic, type: .withResponse)
}

extension ViewController: CBPeripheralDelegate {
    func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
        // Bluetooth 장치의 특성을 찾았을 때의 처리
        for characteristic in service.characteristics! {
            if characteristic.uuid == characteristicUUID {
                // 데이터를 주고 받을 특성과 연결이 이루어졌을 때의 처리
                peripheral.setNotifyValue(true, for: characteristic)
            }
        }
    }
    
    func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
        // 데이터를 수신했을 때의 처리
        let receivedData = characteristic.value
        // 수신한 데이터를 처리
    }
}

위 코드에서 sendDataToDevice 메서드를 호출하여 데이터를 Bluetooth 장치로 전송할 수 있습니다. 데이터를 수신하면 peripheral:didUpdateValueFor: 메서드가 호출되며, 수신한 데이터에 대한 처리 로직을 구현할 수 있습니다.

이와 같이 Swift Core Bluetooth를 사용하면 iOS 기기와 다른 블루투스 장치 간의 데이터 통신을 손쉽게 구현할 수 있습니다. Core Bluetooth 프레임워크의 다른 기능들을 알아보고, 원하는 기능을 구현해보세요.

참고 자료