[swift] Swift Core Bluetooth를 사용한 데이터 저장 및 로드

Swift는 iOS 애플리케이션에서 Bluetooth Low Energy (BLE) 기능을 제어하기 위한 Core Bluetooth 프레임워크를 제공합니다. 이를 사용하여 연결된 BLE 장치와 데이터를 주고받고, 저장 및 로드할 수 있습니다.

이번 예제에서는 Swift Core Bluetooth를 사용하여 BLE 장치와 데이터를 저장하고 로드하는 방법에 대해 알아보겠습니다.

1. BLE 장치와 연결하기

BLE 장치와의 연결은 CBCentralManager 클래스를 사용하여 수행됩니다. 아래의 코드를 참고하여 BLE 장치와 연결하는 함수를 작성해 보겠습니다.

import CoreBluetooth

class BluetoothManager: NSObject, CBCentralManagerDelegate {
    var centralManager: CBCentralManager!
    var peripheral: CBPeripheral?
    
    override init() {
        super.init()
        centralManager = CBCentralManager(delegate: self, queue: nil)
    }
    
    func centralManagerDidUpdateState(_ central: CBCentralManager) {
        if central.state == .poweredOn {
            // BLE 장치와의 연결 시작
            centralManager.scanForPeripherals(withServices: nil, options: nil)
        } else {
            // BLE 장치 연결 불가능
            print("BLE not available")
        }
    }
    
    func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
        // 발견한 BLE 장치와 연결
        self.peripheral = peripheral
        centralManager.stopScan()
        centralManager.connect(self.peripheral!, options: nil)
    }
    
    func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
        // BLE 장치와 연결 완료
        print("Connected to BLE device")
    }
}

위의 코드에서 BluetoothManager 클래스는 CBCentralManagerDelegate를 구현하여 BLE 장치와의 연결 상태 및 결과를 처리합니다. centralManagerDidUpdateState 함수에서 BLE 장치의 상태를 확인한 후, .poweredOn 상태일 경우 scanForPeripherals 함수를 사용하여 주변 BLE 장치를 스캔합니다. didDiscover 함수에서 발견한 장치와 연결을 시도하고, didConnect 함수에서 연결이 완료되었음을 확인합니다.

2. 데이터 저장 및 로드하기

BLE 장치와 연결이 완료된 후, 데이터를 저장하거나 로드하기 위해서는 CBPeripheral 객체를 사용합니다. 아래의 코드를 참고하여 데이터를 저장하고 로드하는 함수를 작성해 보겠습니다.

import CoreBluetooth

class BluetoothManager: NSObject, CBCentralManagerDelegate, CBPeripheralDelegate {
    var centralManager: CBCentralManager!
    var peripheral: CBPeripheral?
    var dataCharacteristic: CBCharacteristic?
    
    override init() {
        super.init()
        centralManager = CBCentralManager(delegate: self, queue: nil)
    }
    
    func centralManagerDidUpdateState(_ central: CBCentralManager) {
        if central.state == .poweredOn {
            // BLE 장치와의 연결 시작
            centralManager.scanForPeripherals(withServices: nil, options: nil)
        } else {
            // BLE 장치 연결 불가능
            print("BLE not available")
        }
    }
    
    func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
        // 발견한 BLE 장치와 연결
        self.peripheral = peripheral
        centralManager.stopScan()
        centralManager.connect(self.peripheral!, options: nil)
    }
    
    func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
        // BLE 장치와 연결 완료
        print("Connected to BLE device")
        self.peripheral?.delegate = self
        self.peripheral?.discoverServices(nil)
    }
    
    func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
        // 발견한 서비스 검색
        if let services = peripheral.services {
            for service in services {
                if service.uuid.uuidString == "YOUR_SERVICE_UUID" {
                    self.peripheral?.discoverCharacteristics(nil, for: service)
                }
            }
        }
    }
    
    func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
        // 발견한 특성 검색
        if let characteristics = service.characteristics {
            for characteristic in characteristics {
                if characteristic.uuid.uuidString == "YOUR_CHARACTERISTIC_UUID" {
                    self.dataCharacteristic = characteristic
                }
            }
        }
    }
    
    func saveData(data: Data) {
        // 데이터 저장
        if let characteristic = self.dataCharacteristic {
            self.peripheral?.writeValue(data, for: characteristic, type: .withResponse)
        }
    }
    
    func loadData() {
        // 데이터 로드
        if let characteristic = self.dataCharacteristic {
            self.peripheral?.readValue(for: characteristic)
        }
    }
    
    func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
        // 데이터 업데이트 확인
        if let data = characteristic.value {
            // 업데이트된 데이터 처리
        }
    }
}

위의 코드에서 BluetoothManager 클래스는 CBPeripheralDelegate를 구현하여 데이터 저장 및 로드 작업을 처리합니다. peripheral(_:didDiscoverServices:) 함수에서 BLE 장치가 제공하는 서비스를 검색하고, 해당하는 서비스를 찾은 후 peripheral(_:didDiscoverCharacteristicsFor:error:) 함수를 통해 특성을 검색합니다. 이후 saveData 함수를 사용하여 데이터를 저장하고, loadData 함수를 사용하여 데이터를 로드합니다. peripheral(_:didUpdateValueFor:error:) 함수에서 데이터의 업데이트를 확인하고 처리합니다.

마무리

위의 예제는 Swift Core Bluetooth를 사용하여 BLE 장치와 데이터를 저장하고 로드하는 방법에 대해 알아보았습니다. Core Bluetooth는 iOS 애플리케이션에서 BLE 기능을 사용하는 데 필수적인 도구이며, 다양한 IoT 및 웨어러블 애플리케이션을 개발하는 데 활용될 수 있습니다.

더 자세한 정보를 얻으려면 Apple Developer Documentation을 참조하세요.