Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
Tags
- 디자인 트렌드
- 머티리얼 디자인
- iOS앱개발올인원패키지Online.
- git
- 스큐어모피즘
- 직장인인강
- git workflow
- viewDidAppear
- 패캠챌린지
- commit messages
- coordinator pattern
- 패스트캠퍼스후기
- 플랫디자인
- 뉴북
- viewDidLoad
- SWIFT
- 패스트캠퍼스
- 코드리팩토링
- 픽셀
- 포인트
- Git Tutorial
- Xcodebuild
- ios
- 입력 개수 제한
- 아이폰
- 직장인자기계발
- commit
- 8 그리드 시스템
- commit message
- 뉴모피즘
Archives
- Today
- Total
왕논의 연구실
CoreBluetooth - 입문 본문
CoreBluetooth
BLE 통신을 iOS에서 다루는 방법
✨ CoreBluetooth란 무엇인가?
CoreBluetooth는 iOS, macOS, watchOS에서
Bluetooth Low Energy (BLE) 통신을 지원하기 위한 애플 프레임워크입니다.
BLE는 저전력 통신 기술로, 소형 디바이스(스마트워치, 피트니스 밴드, IoT 센서 등)와 데이터를 교환할 때 사용합니다.
🛠 CoreBluetooth를 다루는 기본 구조
CoreBluetooth는 2가지 큰 역할로 나뉩니다.
역할 | 클래스 | 설명 |
---|---|---|
Central | CBCentralManager , CBPeripheral |
주변 BLE 기기 스캔 및 연결 (스마트폰처럼 동작) |
Peripheral | CBPeripheralManager , CBMutableCharacteristic , CBMutableService |
BLE 기기 역할 (센서처럼 동작) |
🧩 Central 개발 흐름
iOS에서는 보통 우리가 Central 역할을 합니다. (MiBand 연결하는 것도 Central입니다)
📋 기본 플로우
CBCentralManager
생성centralManager.scanForPeripherals()
호출- 주변 BLE 기기(
CBPeripheral
) 검색 - 원하는 기기 연결
- 서비스(
CBService
) 검색 - 캐릭터리스틱(
CBCharacteristic
) 검색 - 데이터 읽기/쓰기/구독(Notification)
🎯 Central 코드 흐름 예제
import CoreBluetooth
class BLEManager: NSObject, CBCentralManagerDelegate, CBPeripheralDelegate {
var centralManager: CBCentralManager!
var discoveredPeripheral: CBPeripheral?
override init() {
super.init()
centralManager = CBCentralManager(delegate: self, queue: nil)
}
func centralManagerDidUpdateState(_ central: CBCentralManager) {
if central.state == .poweredOn {
centralManager.scanForPeripherals(withServices: nil)
}
}
func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
print("Discovered \(peripheral.name ?? "Unknown")")
discoveredPeripheral = peripheral
centralManager.connect(peripheral, options: nil)
}
func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
print("Connected to \(peripheral.name ?? "Unknown")")
peripheral.delegate = self
peripheral.discoverServices(nil)
}
func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
guard let services = peripheral.services else { return }
for service in services {
peripheral.discoverCharacteristics(nil, for: service)
}
}
func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
guard let characteristics = service.characteristics else { return }
for characteristic in characteristics {
print("Discovered Characteristic: \(characteristic.uuid)")
}
}
}
🧠 CoreBluetooth 핵심 개념 요약
용어 | 설명 |
---|---|
Service | BLE 디바이스의 기능 그룹 (예: 심박수, 배터리) |
Characteristic | 실제 데이터 읽기/쓰기 단위 |
UUID | Service/Characteristic을 구분하는 고유 식별자 |
Read/Write/Notify | 데이터를 읽거나, 쓰거나, 실시간 알림 받는 방법 |
⚡ 주의사항
BLE는 권한이 필요합니다!
➔Info.plist
에 다음을 추가해야 합니다.<key>NSBluetoothAlwaysUsageDescription</key> <string>Bluetooth를 사용하여 주변 기기와 통신합니다.</string>
Simulator에서는 BLE 사용이 불가합니다.
반드시 실기기(iPhone/iPad) 로 테스트하세요!연결 끊김 대비 로
didDisconnectPeripheral
구현도 필수입니다.
🚀 실무 팁
필요한 서비스만 스캔하면 배터리 절약 + 속도 향상
centralManager.scanForPeripherals(withServices: [CBUUID(string: "180D")])
Notification 등록 후 반드시 해제
- 앱 종료 시, 혹은 필요 없을 때
setNotifyValue(false, for: characteristic)
- 앱 종료 시, 혹은 필요 없을 때
Background BLE 통신 필요하면 Info.plist에 다음 추가:
<key>UIBackgroundModes</key> <array> <string>bluetooth-central</string> </array>
📚 추천 학습 리소스
- Apple 공식 문서: CoreBluetooth Framework
- Raywenderlich 튜토리얼: iOS BLE Programming
- GitHub 오픈소스 프로젝트들 분석 (예: MiBand SDK, BLEScanner)
'iOS > Swift' 카테고리의 다른 글
iOS 화면 구성 시 자주 사용하는 Override 함수 정리 (UIView / UIViewController) (0) | 2025.04.19 |
---|---|
Swift XCTest 정리 - 입문 (0) | 2025.04.15 |
CAEmitterCell (0) | 2025.04.12 |
CAEmitterLayer (0) | 2025.04.12 |
OSLog 요소 (0) | 2025.04.11 |