이번 포스팅에서는 Swift 환경에서 Bluetooth 기기를 검색하고, 기기의 UUID를 찾아서 연결하는 방법에 대해 알아보겠습니다. Bluetooth 기술은 많은 스마트 기기와 통신하는 데 사용되며, iOS 앱 개발에서도 중요한 기능 중 하나로 자리잡고 있습니다.
Bluetooth Low Energy(LE)란?
Bluetooth LE는 블루투스의 저전력 버전으로, IoT(사물인터넷) 기기와 모바일 기기 간의 통신을 최적화하는 데 주로 사용됩니다. 예를 들어, 헬스케어 기기, 스마트 웨어러블 장치 등이 이에 해당합니다.
UUID란?
UUID(고유 식별자)는 블루투스 LE 장치를 구별하는 데 사용되는 고유한 문자열입니다. 기기마다 고유의 UUID가 할당되어 있으며, 이를 통해 특정 블루투스 장치와 연결할 수 있습니다.
예제 구현을 위한 준비
이 예제에서는 다음과 같은 요소들이 필요합니다:
- iOS 13 이상
- Xcode 11 이상
- CoreBluetooth 프레임워크
프로젝트를 생성한 후, CoreBluetooth 프레임워크를 추가해주어야 합니다. Xcode의 프로젝트 내비게이터에서 프로젝트를 선택하고, 'General' 탭의 'Frameworks, Libraries, and Embedded Content' 섹션에 CoreBluetooth를 추가합니다.
BluetoothManager.swift 클래스 생성하기
다음으로, Bluetooth 기기를 검색하고 연결하는 로직을 담당할 BluetoothManager 클래스를 생성하겠습니다.
import CoreBluetooth
class BluetoothManager: 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 {
print("Bluetooth가 켜져 있습니다.")
// Bluetooth 기기 검색 시작
centralManager.scanForPeripherals(withServices: nil, options: nil)
} else {
print("Bluetooth가 꺼져있습니다.")
}
}
func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
print("발견된 장치: \(peripheral.name ?? "재설정된 장치")")
// UUID 확인
if let uuid = peripheral.identifier.uuidString {
print("장치 UUID: \(uuid)")
}
// 특정 UUID를 확인하고 연결 시도
if peripheral.identifier.uuidString == "YOUR_TARGET_UUID" {
discoveredPeripheral = peripheral
centralManager.connect(peripheral, options: nil)
}
}
func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
print("\(peripheral.name ?? "재설정된 장치")에 연결되었습니다.")
// 연결 후 작업 수행 가능
}
func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) {
print("\(peripheral.name ?? "재설정된 장치")와의 연결이 끊겼습니다.")
}
}
UIViewController에서 BluetoothManager 사용하기
BluetoothManager 클래스를 사용하기 위해 UIViewController에서 인스턴스를 생성하고 초기화해야 합니다.
import UIKit
class ViewController: UIViewController {
var bluetoothManager: BluetoothManager!
override func viewDidLoad() {
super.viewDidLoad()
bluetoothManager = BluetoothManager()
}
}
앱 권한 설정
iOS 앱에서 Bluetooth 기능을 사용하기 위해, Info.plist 파일에 권한 요청 메시지를 추가해야 합니다. 다음의 두 키를 추가해 주세요:
- NSBluetoothAlwaysUsageDescription : Bluetooth 사용에 대한 설명
- NSBluetoothPeripheralUsageDescription : BLE 주변장치에 대한 접근 요청
예를 들어, 다음과 같은 설명을 추가할 수 있습니다:
NSBluetoothAlwaysUsageDescription
이 앱은 Bluetooth에 연결하여 기기와 데이터를 교환합니다.
NSBluetoothPeripheralUsageDescription
이 앱은 주변 Bluetooth 기기에 접근하기 위해 Bluetooth를 사용합니다.
앱을 실행하면 Bluetooth 기기를 찾고, 특정 UUID를 가진 기기를 연결할 수 있습니다.
마무리
이번 포스팅에서는 Swift를 활용하여 Bluetooth 기기를 검색하고, 특정 UUID에 해당하는 기기와 연결하는 방법에 대해 알아보았습니다. 이를 바탕으로 더 복잡한 Bluetooth 기능 및 데이터를 처리하는 프로젝트를 진행해 보세요. 추가적인 질문이 있으시면 댓글 남겨주시기 바랍니다.
'IT > Swift' 카테고리의 다른 글
Swift의 NotificationCenter: 메모리 관리를 위한 효율적인 이벤트 전달 (0) | 2025.03.13 |
---|---|
Xcode 사용법: 애플 개발의 시작점 (1) | 2025.02.27 |
스위프트 인터페이스 스토리보드로 Hello World 앱 만들기 (0) | 2025.02.27 |
Xcode란 무엇인가요? (0) | 2025.02.27 |
Swift4 Hello, World Xcode 프로젝트 생성 하기! (0) | 2019.07.07 |