[ios] Core Bluetooth 사용하기

iOS 앱을 개발할 때 Bluetooth를 사용하여 외부 장치와 상호 작용해야 하는 경우가 종종 있습니다. Core Bluetooth 프레임워크를 사용하면 iOS 기기가 Bluetooth Low Energy(BLE)를 통해 다른 Bluetooth 장치와 통신할 수 있게 됩니다.

이 기술 블로그에서는 Core Bluetooth를 사용하여 iOS 앱에서 Bluetooth 장치와의 상호 작용을 설정하는 방법에 대해 다루겠습니다.

1. Core Bluetooth 설정

Core Bluetooth를 사용하려면 Xcode 프로젝트에서 Core Bluetooth 프레임워크를 추가해야 합니다. 이를 위해 프로젝트 설정에서 “Linked Frameworks and Libraries” 섹션에 Core Bluetooth를 추가하거나, 코드에서 import CoreBluetooth 문을 추가해야 합니다.

2. Bluetooth 장치 스캔

Bluetooth 장치를 스캔하여 찾으려면 CBCentralManager 클래스의 인스턴스를 생성하고, scanForPeripherals 메서드를 사용하여 주변에 있는 Bluetooth 장치를 스캔합니다.

import CoreBluetooth

class BluetoothManager: NSObject, CBCentralManagerDelegate {
    var centralManager: CBCentralManager!

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

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

    func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
        // 발견된 Bluetooth 장치 처리
    }
}

3. Bluetooth 장치와 연결

찾은 Bluetooth 장치 중에서 원하는 장치를 선택하고, connect 메서드를 사용하여 해당 장치에 연결합니다.

func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
    if peripheral.name == "MyDevice" {
        central.connect(peripheral, options: nil)
    }
}

위의 코드에서 “MyDevice”는 연결하려는 Bluetooth 장치의 이름입니다.

4. 데이터 교환

Bluetooth 장치와 연결된 후에는 데이터를 교환할 수 있습니다. Bluetooth 장치의 서비스와 특성을 발견하고, 데이터를 읽거나 쓸 수 있습니다.

위 과정을 통해 Core Bluetooth를 사용하여 iOS 앱과 Bluetooth 장치 간에 상호 작용할 수 있습니다. 추가적으로, Core Bluetooth 프레임워크 문서를 참조하여 더 자세한 정보를 확인할 수 있습니다.

더 자세한 내용은 Apple Developer Documentation를 참고하세요.

그럼 성공적인 Bluetooth 통신으로 좋은 결과를 얻길 바랍니다!