[swift] Swift Core Bluetooth로 장치 간 데이터 전송하기

Swift Core Bluetooth를 사용하여 iOS 앱에서 장치 간에 데이터를 전송하는 방법에 대해 알아보겠습니다.

목차

  1. Core Bluetooth 소개
  2. 장치 검색
  3. 연결 설정
  4. 데이터 전송
  5. 참고 자료

1. Core Bluetooth 소개

Core Bluetooth는 iOS 기기 간에 무선으로 데이터를 전송할 수 있는 프레임워크입니다. 이를 사용하여 서로 다른 iOS 기기 간에 데이터를 주고받을 수 있습니다.

2. 장치 검색

Core Bluetooth를 사용하여 주변에 있는 Bluetooth 장치를 검색할 수 있습니다. CBCentralManager를 사용하여 주변 장치를 검색하고, 해당 장치를 리스트로 표시하는 등의 작업을 수행할 수 있습니다.

다음은 장치 검색을 시작하는 예제 코드입니다.

import CoreBluetooth

class DeviceDiscovery: 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) {
        // 검색된 장치 처리
        // ...
    }
}

위 코드는 CBCentralManagerDelegate 프로토콜을 채택하여 centralManagerDidUpdateState 메서드를 구현하여 주변 장치 검색을 시작하는 예제입니다. centralManager(_:didDiscover:advertisementData:rssi:) 메서드에서 검색된 장치를 처리할 수 있습니다.

3. 연결 설정

검색된 장치를 선택하여 연결을 설정할 수 있습니다. CBPeripheral 클래스의 connect(_:options:) 메서드를 사용하여 선택한 장치와 연결을 설정할 수 있습니다.

다음은 연결을 설정하는 예제 코드입니다.

func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
    if peripheral.name == "My Device" {
        central.stopScan() // 검색 중지
        
        // 연결 설정
        central.connect(peripheral, options: nil)
    }
}

위 코드는 검색된 장치 중에서 “My Device”라는 이름을 가진 장치를 찾아 연결을 설정하는 예제입니다. central.stopScan()은 장치 검색을 중지하는 메서드입니다.

4. 데이터 전송

연결이 설정된 이후, CBPeripheral 클래스의 writeValue(_:for:withResponse:) 메서드를 사용하여 데이터를 전송할 수 있습니다.

다음은 데이터 전송을 하는 예제 코드입니다.

func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
    // 데이터 전송
    let data = "Hello, Bluetooth!".data(using: .utf8)
    peripheral.writeValue(data, for: characteristic, type: .withResponse)
}

위 코드는 연결이 설정된 이후, “Hello, Bluetooth!”라는 데이터를 전송하는 예제입니다.

5. 참고 자료

위의 참고 자료는 Core Bluetooth 프레임워크를 사용하는 방법에 대해서 상세하게 설명하고 있습니다. 추가적인 정보를 원하신다면 위 링크를 참고하여보시기 바랍니다.