[swift] Swift Core Bluetooth와 백그라운드 작업

iOS 애플리케이션을 개발할 때 Bluetooth를 사용해 외부 장치와 통신해야 할 때가 있습니다. Swift에서는 Core Bluetooth 프레임워크를 통해 Bluetooth 장치와의 상호 작용을 위한 API를 제공합니다.

이번 블로그 포스트에서는 Swift Core Bluetooth를 사용하여 Bluetooth 장치와의 통신을 구현할 때 백그라운드에서 작업하는 방법에 대해 알아보겠습니다.

Core Bluetooth 백그라운드 작업 설정

iOS에서 Core Bluetooth를 사용하여 백그라운드 상태에서 장치와 통신하려면 몇 가지 추가 설정이 필요합니다. 먼저 앱의 Info.plist 파일을 열고 다음 키를 추가해야 합니다.

<key>UIBackgroundModes</key>
<array>
    <string>bluetooth-central</string>
</array>

이는 앱이 백그라운드에서 Bluetooth 통신을 수행할 수 있다는 것을 시스템에 알리는 역할을 합니다.

백그라운드에서 Bluetooth 장치 탐색

Bluetooth 장치 탐색을 위해 Core Bluetooth의 CBCentralManager를 사용합니다. 백그라운드에서 탐색을 수행하려면 다음과 같이 CBCentralManagerOptionRestoreIdentifierKey 옵션을 사용하여 CBCentralManager 인스턴스를 초기화해야 합니다.

let centralManager = CBCentralManager(delegate: self, queue: nil, options: [CBCentralManagerOptionRestoreIdentifierKey: "YourRestoreIdentifier"])

여기에서 “YourRestoreIdentifier”는 앱을 백그라운드에서 복원할 때 사용될 식별자입니다.

백그라운드에서 데이터 수신

페리퍼런스 등의 데이터를 백그라운드에서 수신해야 할 때는 Core Bluetooth의 CBPeripheralDelegate 프로토콜을 구현해야 합니다. 데이터를 받기 위해 peripheral(_:didUpdateValueFor:error:) 메서드를 사용할 수 있습니다.

func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
    guard let value = characteristic.value else { return }
    // 수신한 데이터 처리
}

이 메서드는 백그라운드에서 데이터가 업데이트될 때마다 호출되며, 받은 데이터는 characteristic.value 속성에서 사용할 수 있습니다.

백그라운드에서 동작하는 Central Manager 유지

백그라운드에서 Bluetooth 장치와의 연결을 유지하려면 CBCentralManagerDelegate 프로토콜의 centralManager(_:willRestoreState:) 메서드를 구현해야 합니다.

func centralManager(_ central: CBCentralManager, willRestoreState dict: [String : Any]) {
    // 백그라운드 상태에서 복원되는 동안 연결 상태를 관리
}

이 메서드는 앱이 백그라운드에서 실행 중이거나 종료되었다가 다시 실행될 때 호출됩니다. 여기에서 연결 상태를 관리하는 로직을 구현할 수 있습니다.

결론

Swift Core Bluetooth를 사용하여 Bluetooth 장치와 통신을 구현하는 것은 매우 간단하면서도 강력합니다. 위에서 설명한 것처럼 백그라운드에서 작업하기 위해서는 몇 가지 설정과 프로토콜을 구현해야 합니다. 이를 통해 앱이 백그라운드에서도 원활하게 Bluetooth 통신을 수행할 수 있습니다.

이외에도 Swift Core Bluetooth에는 더 많은 기능과 API가 있으니 관심 있는 분들은 공식 문서를 참조해보시기 바랍니다.

참고 자료: