[ios] Core Bluetooth와 백그라운드 실행

Core Bluetooth는 iOS 앱에서 Bluetooth LE(저전력) 장치와의 통신을 가능케 하는 프레임워크입니다. 앱을 백그라운드에서도 Bluetooth 장치와 통신할 수 있게 하려면 추가적인 설정이 필요합니다.

Core Bluetooth 백그라운드 실행

iOS에서 Core Bluetooth를 백그라운드에서 실행하려면 다음 단계를 따르세요.

  1. Info.plist 설정: Info.plist 파일에 UIBackgroundModes 키를 추가하고 bluetooth-central 값을 설정합니다. 이렇게 하면 앱이 백그라운드에서 Bluetooth 장치와 상호작용할 수 있습니다.

     <key>UIBackgroundModes</key>
     <array>
         <string>bluetooth-central</string>
     </array>
    
  2. CBCentralManager 설정: CBCentralManager 인스턴스를 생성할 때 queue 매개변수에 nil이 아닌 값을 전달하여 백그라운드 동작을 활성화 합니다.

     let centralQueue = DispatchQueue(label: "com.example.MyCentralQueue", attributes: .concurrent)
     let centralManager = CBCentralManager(delegate: self, queue: centralQueue)
    
  3. 백그라운드 실행 지원 코드 추가: 앱의 델리게이트 메서드 내에 적절한 코드를 추가하여 백그라운드에서 Bluetooth 이벤트를 처리합니다.

     func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
         // 백그라운드 실행 코드 추가
         centralManager = CBCentralManager(delegate: self, queue: centralQueue, options: [CBAdvertisementDataLocalNameKey: "MyPeripheral"])
         return true
     }
    

이제 Core Bluetooth를 사용하여 iOS 앱이 백그라운드에서도 Bluetooth LE 장치와 상호작용할 수 있게 되었습니다.

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

위의 코드는 Swift 언어를 사용한 예시입니다.


참고 자료