콘텐츠 대표 이미지 - Swift를 이용한 블루투스 통신 구현

Swift를 이용한 블루투스 통신 구현

안녕하세요 여러분! 오늘은 iOS 개발자라면 한 번쯤 마주치게 되는 블루투스 통신 구현에 대해 함께 알아볼게요. 🚀 요즘 웨어러블 기기나 IoT 디바이스와의 연동이 트렌드인데, 이런 기술 스택 하나 갖추면 재능넷 같은 플랫폼에서도 인기 개발자 될 수 있겠죠? ㅋㅋㅋ 실제로 재능넷에서 블루투스 통신 관련 프로젝트 의뢰가 꽤 많이 올라온다고 하더라구요! 😎

Swift로 블루투스 통신을 구현하는 건 처음엔 좀 어려워 보일 수 있지만, Core Bluetooth 프레임워크만 제대로 이해하면 생각보다 쉽게 구현할 수 있어요. 그럼 이제부터 진짜 꿀팁들 알려드릴게요! 바로 고고! 📱✨

1. Core Bluetooth 프레임워크 이해하기 🧩

일단 블루투스 통신을 구현하려면 애플의 Core Bluetooth 프레임워크를 알아야 해요. 이 프레임워크는 BLE(Bluetooth Low Energy) 기기와 통신할 수 있게 해주는 핵심 도구에요.

블루투스 통신에서는 두 가지 주요 역할이 있어요:

  1. Central(센트럴): 주변 기기를 스캔하고 연결을 시도하는 역할 (보통 우리 iOS 기기)
  2. Peripheral(페리퍼럴): 연결을 기다리고 데이터를 제공하는 역할 (보통 외부 블루투스 기기)

이 개념 헷갈리면 안 돼요! 우리 폰이 보통 센트럴이고, 연결하려는 이어폰이나 스마트워치가 페리퍼럴이라고 생각하면 됨! 😉

그리고 블루투스 통신에서 꼭 알아야 할 용어들이 있는데요:

  1. Service(서비스): 특정 기능이나 데이터의 집합
  2. Characteristic(특성): 실제 데이터가 저장되는 곳
  3. UUID(Universally Unique Identifier): 서비스와 특성을 식별하는 고유 ID

이거 진짜 중요한데, 블루투스 기기는 여러 서비스를 가질 수 있고, 각 서비스는 여러 특성을 가질 수 있어요. 마치 폴더와 파일 구조처럼요! 폴더(서비스) 안에 파일(특성)이 있는 거죠. ㅋㅋㅋ 이렇게 생각하면 쉽죠?

2. 블루투스 권한 설정하기 🔐

블루투스 기능을 사용하려면 앱에 권한을 추가해야 해요. iOS는 사용자 프라이버시에 엄청 신경쓰니까요! 😅

Info.plist 파일에 다음 키를 추가해야 해요:

NSBluetoothAlwaysUsageDescription

이 키에는 "블루투스 기기와 연결하여 데이터를 주고받기 위해 블루투스 권한이 필요합니다." 같은 설명을 추가하면 돼요.

iOS 13 이상에서는 백그라운드에서도 블루투스를 사용하려면 추가 설정이 필요해요:

UIBackgroundModes: bluetooth-central, bluetooth-peripheral

이거 안 하면 앱이 백그라운드로 가면 연결이 끊길 수 있으니 주의하세요! 진짜 많은 분들이 이거 때문에 삽질한다니까요... ㅋㅋㅋ 🤦‍♂️

3. Central 역할 구현하기 (기기 스캔 및 연결) 🔍

이제 본격적으로 코드를 작성해볼게요! 먼저 센트럴 매니저를 생성하고 주변 기기를 스캔하는 코드예요:

import UIKit
import CoreBluetooth

class BluetoothViewController: UIViewController {
    
    // 센트럴 매니저 인스턴스 생성
    var centralManager: CBCentralManager!
    var discoveredPeripheral: CBPeripheral?
    
    // 찾고자 하는 서비스 UUID
    let targetServiceUUID = CBUUID(string: "YOUR_SERVICE_UUID")
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 센트럴 매니저 초기화
        centralManager = CBCentralManager(delegate: self, queue: nil)
    }
    
    // 스캔 시작 메서드
    func startScanning() {
        centralManager.scanForPeripherals(withServices: [targetServiceUUID], options: nil)
        print("스캔 시작했어요! 🔍")
        
        // 10초 후 스캔 중지
        DispatchQueue.main.asyncAfter(deadline: .now() + 10.0) {
            self.stopScanning()
        }
    }
    
    // 스캔 중지 메서드
    func stopScanning() {
        centralManager.stopScan()
        print("스캔 중지했어요! ✋")
    }
}

그리고 CBCentralManagerDelegate 프로토콜을 구현해야 해요:

extension BluetoothViewController: CBCentralManagerDelegate {
    
    // 블루투스 상태 변경 시 호출
    func centralManagerDidUpdateState(_ central: CBCentralManager) {
        switch central.state {
        case .poweredOn:
            print("블루투스 켜졌어요! 스캔 시작할게요~ 😎")
            startScanning()
        case .poweredOff:
            print("블루투스가 꺼져있어요! 켜주세요! 😱")
        case .unsupported:
            print("이 기기는 블루투스를 지원하지 않아요 ㅠㅠ 😢")
        case .unauthorized:
            print("블루투스 권한이 없어요! 설정에서 허용해주세요! 🔒")
        case .resetting:
            print("블루투스 연결이 재설정 중이에요! 잠시만요~ ⏳")
        case .unknown:
            print("알 수 없는 상태에요! 뭔가 이상해요! 🤔")
        @unknown default:
            print("미래에 추가될 수도 있는 상태에요! 👽")
        }
    }
    
    // 주변 기기 발견 시 호출
    func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
        print("기기 발견! 이름: \(peripheral.name ?? "이름 없음") 📱")
        
        // 원하는 기기를 찾았다면 연결 시도
        if peripheral.name == "YOUR_DEVICE_NAME" {
            discoveredPeripheral = peripheral
            centralManager.connect(peripheral, options: nil)
            stopScanning() // 연결 시도 시 스캔 중지
        }
    }
    
    // 기기 연결 성공 시 호출
    func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
        print("연결 성공! 이제 서비스를 찾아볼게요~ 🎉")
        peripheral.delegate = self
        peripheral.discoverServices([targetServiceUUID])
    }
    
    // 기기 연결 실패 시 호출
    func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) {
        print("연결 실패했어요 ㅠㅠ 에러: \(error?.localizedDescription ?? "알 수 없는 에러") 😭")
    }
    
    // 기기 연결 끊김 시 호출
    func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) {
        print("연결이 끊겼어요! 다시 연결할게요~ 🔄")
        centralManager.connect(peripheral, options: nil)
    }
}

이제 CBPeripheralDelegate 프로토콜도 구현해야 해요:

extension BluetoothViewController: CBPeripheralDelegate {
    
    // 서비스 발견 시 호출
    func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
        guard error == nil else {
            print("서비스 발견 중 에러 발생: \(error!.localizedDescription) 😱")
            return
        }
        
        if let services = peripheral.services {
            for service in services {
                print("서비스 발견: \(service.uuid) 🧩")
                // 특성 찾기
                peripheral.discoverCharacteristics(nil, for: service)
            }
        }
    }
    
    // 특성 발견 시 호출
    func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
        guard error == nil else {
            print("특성 발견 중 에러 발생: \(error!.localizedDescription) 😱")
            return
        }
        
        if let characteristics = service.characteristics {
            for characteristic in characteristics {
                print("특성 발견: \(characteristic.uuid) 📊")
                
                // 읽기 가능한 특성이면 읽기 요청
                if characteristic.properties.contains(.read) {
                    peripheral.readValue(for: characteristic)
                }
                
                // 알림 가능한 특성이면 알림 구독
                if characteristic.properties.contains(.notify) {
                    peripheral.setNotifyValue(true, for: characteristic)
                }
            }
        }
    }
    
    // 특성 값 업데이트 시 호출
    func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
        guard error == nil else {
            print("값 읽기 중 에러 발생: \(error!.localizedDescription) 😱")
            return
        }
        
        if let data = characteristic.value {
            // 데이터 처리
            print("받은 데이터: \(data.hexString) 📲")
            
            // 예: 문자열로 변환
            if let string = String(data: data, encoding: .utf8) {
                print("문자열 데이터: \(string) 💬")
            }
        }
    }
}

위 코드에서 hexString은 Data 확장으로 구현해야 해요:

extension Data {
    var hexString: String {
        return self.map { String(format: "%02hhx", $0) }.joined()
    }
}

이렇게 하면 기본적인 블루투스 스캔, 연결, 데이터 읽기가 가능해요! 근데 이거 그냥 복붙하지 말고 이해하면서 써야 나중에 디버깅할 때 덜 힘들어요~ ㅋㅋㅋ 😅

4. 데이터 쓰기(Write) 구현하기 ✍️

이제 블루투스 기기로 데이터를 보내는 방법을 알아볼게요. 데이터를 보내려면 쓰기 가능한 특성을 찾아서 데이터를 전송해야 해요:

// 데이터 쓰기 메서드
func writeData(data: Data, to peripheral: CBPeripheral, characteristic: CBCharacteristic) {
    // 쓰기 가능한지 확인
    if characteristic.properties.contains(.write) {
        peripheral.writeValue(data, for: characteristic, type: .withResponse)
        print("데이터 전송 요청했어요! 응답 기다리는 중... ⏳")
    } else if characteristic.properties.contains(.writeWithoutResponse) {
        peripheral.writeValue(data, for: characteristic, type: .withoutResponse)
        print("데이터 전송 완료! (응답 없음) ✅")
    } else {
        print("이 특성은 쓰기를 지원하지 않아요! 😭")
    }
}

그리고 쓰기 응답을 처리하는 델리게이트 메서드도 구현해야 해요:

// 데이터 쓰기 완료 시 호출 (withResponse 타입일 때만)
func peripheral(_ peripheral: CBPeripheral, didWriteValueFor characteristic: CBCharacteristic, error: Error?) {
    guard error == nil else {
        print("데이터 쓰기 중 에러 발생: \(error!.localizedDescription) 😱")
        return
    }
    
    print("데이터 쓰기 성공! 👍")
}

이제 실제로 데이터를 보내려면 이렇게 하면 돼요:

// 문자열 데이터 보내기 예시
func sendTextMessage(message: String, to peripheral: CBPeripheral, characteristic: CBCharacteristic) {
    guard let data = message.data(using: .utf8) else {
        print("문자열을 데이터로 변환할 수 없어요! 😵")
        return
    }
    
    writeData(data: data, to: peripheral, characteristic: characteristic)
}

// 숫자 데이터 보내기 예시
func sendNumberValue(value: UInt8, to peripheral: CBPeripheral, characteristic: CBCharacteristic) {
    let data = Data([value])
    writeData(data: data, to: peripheral, characteristic: characteristic)
}

진짜 많은 분들이 withResponse와 withoutResponse의 차이를 헷갈려 하시는데, 간단히 설명하자면:

  1. withResponse: 데이터 전송 후 기기로부터 확인 응답을 받음 (안전하지만 느림)
  2. withoutResponse: 확인 응답 없이 데이터만 전송 (빠르지만 전송 성공 여부 확인 불가)

상황에 맞게 선택하면 되는데, 중요한 데이터는 withResponse로 보내는 게 좋겠죠? ㅋㅋㅋ 🤓

Central iOS 기기 CBCentralManager Peripheral 블루투스 기기 CBPeripheralManager 스캔 및 연결 서비스 & 특성 탐색 데이터 송수신 Swift Core Bluetooth 통신 구조 Central과 Peripheral 간의 통신 흐름

5. Peripheral 역할 구현하기 (기기 역할) 📱

지금까지는 iOS 기기가 센트럴 역할을 하는 경우를 살펴봤는데, iOS 기기가 페리퍼럴 역할을 할 수도 있어요! 이건 다른 기기가 우리 앱에 연결해서 데이터를 주고받을 때 필요해요.

페리퍼럴 역할을 구현하는 코드는 이렇게 생겼어요:

import UIKit
import CoreBluetooth

class PeripheralViewController: UIViewController {
    
    var peripheralManager: CBPeripheralManager!
    var transferCharacteristic: CBMutableCharacteristic?
    var serviceUUID = CBUUID(string: "YOUR_SERVICE_UUID")
    var characteristicUUID = CBUUID(string: "YOUR_CHARACTERISTIC_UUID")
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 페리퍼럴 매니저 초기화
        peripheralManager = CBPeripheralManager(delegate: self, queue: nil)
    }
    
    // 서비스 및 특성 설정
    func setupService() {
        // 특성 생성
        transferCharacteristic = CBMutableCharacteristic(
            type: characteristicUUID,
            properties: [.read, .write, .notify],
            value: nil,
            permissions: [.readable, .writeable]
        )
        
        // 서비스 생성
        let service = CBMutableService(type: serviceUUID, primary: true)
        service.characteristics = [transferCharacteristic!]
        
        // 서비스 추가
        peripheralManager.add(service)
    }
    
    // 광고 시작
    func startAdvertising() {
        peripheralManager.startAdvertising([
            CBAdvertisementDataServiceUUIDsKey: [serviceUUID],
            CBAdvertisementDataLocalNameKey: "내 iOS 기기"
        ])
        print("광고 시작했어요! 다른 기기가 나를 발견할 수 있어요~ 📢")
    }
    
    // 데이터 전송 (구독 중인 센트럴에게)
    func sendData(data: Data) {
        guard let characteristic = transferCharacteristic else { return }
        
        // 데이터 업데이트 및 구독자에게 알림
        let success = peripheralManager.updateValue(
            data,
            for: characteristic,
            onSubscribedCentrals: nil // nil이면 모든 구독자에게 전송
        )
        
        if success {
            print("데이터 전송 성공! 📤")
        } else {
            print("전송 큐가 가득 차서 나중에 다시 시도할게요~ 🔄")
        }
    }
}

그리고 CBPeripheralManagerDelegate 프로토콜 구현도 필요해요:

extension PeripheralViewController: CBPeripheralManagerDelegate {
    
    // 블루투스 상태 변경 시 호출
    func peripheralManagerDidUpdateState(_ peripheral: CBPeripheralManager) {
        switch peripheral.state {
        case .poweredOn:
            print("블루투스 켜졌어요! 서비스 설정하고 광고 시작할게요~ 😎")
            setupService()
            startAdvertising()
        case .poweredOff:
            print("블루투스가 꺼져있어요! 켜주세요! 😱")
        case .unsupported:
            print("이 기기는 블루투스를 지원하지 않아요 ㅠㅠ 😢")
        case .unauthorized:
            print("블루투스 권한이 없어요! 설정에서 허용해주세요! 🔒")
        case .resetting:
            print("블루투스 연결이 재설정 중이에요! 잠시만요~ ⏳")
        case .unknown:
            print("알 수 없는 상태에요! 뭔가 이상해요! 🤔")
        @unknown default:
            print("미래에 추가될 수도 있는 상태에요! 👽")
        }
    }
    
    // 센트럴로부터 읽기 요청 시 호출
    func peripheralManager(_ peripheral: CBPeripheralManager, didReceiveRead request: CBATTRequest) {
        // 요청된 특성이 우리 것인지 확인
        guard request.characteristic.uuid == transferCharacteristic?.uuid else {
            peripheral.respond(to: request, withResult: .attributeNotFound)
            return
        }
        
        // 데이터 준비
        let responseData = "안녕하세요! 이것은 읽기 응답이에요.".data(using: .utf8)!
        
        // 요청 범위 확인
        if request.offset > responseData.count {
            peripheral.respond(to: request, withResult: .invalidOffset)
            return
        }
        
        // 응답 데이터 설정
        request.value = responseData.subdata(in: request.offset..<responseData.count)
        
        // 응답 전송
        peripheral.respond(to: request, withResult: .success)
        print("읽기 요청에 응답했어요! 📤")
    }
    
    // 센트럴로부터 쓰기 요청 시 호출
    func peripheralManager(_ peripheral: CBPeripheralManager, didReceiveWrite requests: [CBATTRequest]) {
        for request in requests {
            // 요청된 특성이 우리 것인지 확인
            guard request.characteristic.uuid == transferCharacteristic?.uuid,
                  let value = request.value else {
                peripheral.respond(to: request, withResult: .attributeNotFound)
                continue
            }
            
            // 데이터 처리
            if let string = String(data: value, encoding: .utf8) {
                print("받은 데이터: \(string) 📥")
            } else {
                print("받은 데이터: \(value.hexString) 📥")
            }
            
            // 응답 전송
            peripheral.respond(to: request, withResult: .success)
        }
    }
    
    // 센트럴이 특성 구독 시작 시 호출
    func peripheralManager(_ peripheral: CBPeripheralManager, central: CBCentral, didSubscribeTo characteristic: CBCharacteristic) {
        print("센트럴이 구독을 시작했어요! 이제 데이터를 보낼 수 있어요~ 🎉")
        
        // 환영 메시지 전송
        if let welcomeData = "구독 시작! 환영합니다!".data(using: .utf8) {
            sendData(data: welcomeData)
        }
    }
    
    // 센트럴이 특성 구독 중지 시 호출
    func peripheralManager(_ peripheral: CBPeripheralManager, central: CBCentral, didUnsubscribeFrom characteristic: CBCharacteristic) {
        print("센트럴이 구독을 중지했어요! 더 이상 데이터를 보낼 수 없어요~ 👋")
    }
    
    // 데이터 전송 준비 완료 시 호출
    func peripheralManagerIsReady(toUpdateSubscribers peripheral: CBPeripheralManager) {
        print("전송 큐에 공간이 생겼어요! 이제 데이터를 다시 보낼 수 있어요~ 🔄")
        // 여기서 이전에 실패한 데이터 전송을 다시 시도할 수 있어요
    }
}

이렇게 하면 iOS 기기가 블루투스 기기 역할을 할 수 있어요! 예를 들어, 두 대의 iPhone 간에 블루투스로 데이터를 주고받는 채팅 앱 같은 걸 만들 수 있죠. 근데 이거 생각보다 배터리 많이 먹으니까 주의하세요! ㅋㅋㅋ 🔋

6. 실전 예제: 블루투스 채팅 앱 구현하기 💬

이제 실제로 블루투스 채팅 앱을 만들어볼게요! 이 예제는 두 대의 iOS 기기 간에 메시지를 주고받는 간단한 채팅 앱이에요.

먼저 채팅 메시지를 표시할 UI를 만들고, 메시지 전송 기능을 구현해볼게요:

import UIKit
import CoreBluetooth

class ChatViewController: UIViewController {
    
    // UI 요소
    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var messageTextField: UITextField!
    @IBOutlet weak var sendButton: UIButton!
    @IBOutlet weak var connectionStatusLabel: UILabel!
    
    // 블루투스 관련 변수
    var centralManager: CBCentralManager!
    var peripheralManager: CBPeripheralManager!
    var discoveredPeripheral: CBPeripheral?
    var transferCharacteristic: CBCharacteristic?
    var serviceUUID = CBUUID(string: "E20A39F4-73F5-4BC4-A12F-17D1AD07A961")
    var characteristicUUID = CBUUID(string: "08590F7E-DB05-467E-8757-72F6FAEB13D4")
    
    // 채팅 메시지 저장
    var messages: [(text: String, isMine: Bool)] = []
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 테이블뷰 설정
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(UINib(nibName: "MessageCell", bundle: nil), forCellReuseIdentifier: "MessageCell")
        
        // 블루투스 매니저 초기화
        centralManager = CBCentralManager(delegate: self, queue: nil)
        peripheralManager = CBPeripheralManager(delegate: self, queue: nil)
        
        // UI 초기 설정
        connectionStatusLabel.text = "연결 대기 중..."
        sendButton.isEnabled = false
    }
    
    // 메시지 전송 버튼 액션
    @IBAction func sendButtonTapped(_ sender: UIButton) {
        guard let messageText = messageTextField.text, !messageText.isEmpty else { return }
        
        // 메시지 전송
        sendMessage(messageText)
        
        // UI 업데이트
        messages.append((messageText, true))
        tableView.reloadData()
        messageTextField.text = ""
        
        // 테이블뷰 스크롤
        scrollToBottom()
    }
    
    // 메시지 전송 메서드
    func sendMessage(_ message: String) {
        guard let data = message.data(using: .utf8) else { return }
        
        // 센트럴 모드에서 전송
        if let peripheral = discoveredPeripheral, let characteristic = transferCharacteristic {
            peripheral.writeValue(data, for: characteristic, type: .withResponse)
        }
        
        // 페리퍼럴 모드에서 전송
        if let characteristic = transferCharacteristic {
            peripheralManager.updateValue(data, for: characteristic as! CBMutableCharacteristic, onSubscribedCentrals: nil)
        }
    }
    
    // 테이블뷰 맨 아래로 스크롤
    func scrollToBottom() {
        if messages.count > 0 {
            let indexPath = IndexPath(row: messages.count - 1, section: 0)
            tableView.scrollToRow(at: indexPath, at: .bottom, animated: true)
        }
    }
}

이제 테이블뷰 델리게이트와 데이터소스를 구현해볼게요:

extension ChatViewController: UITableViewDelegate, UITableViewDataSource {
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return messages.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "MessageCell", for: indexPath) as! MessageCell
        
        let message = messages[indexPath.row]
        cell.configure(with: message.text, isMine: message.isMine)
        
        return cell
    }
}

그리고 블루투스 델리게이트도 구현해야 해요:

// 센트럴 매니저 델리게이트
extension ChatViewController: CBCentralManagerDelegate {
    
    func centralManagerDidUpdateState(_ central: CBCentralManager) {
        if central.state == .poweredOn {
            centralManager.scanForPeripherals(withServices: [serviceUUID], options: nil)
            connectionStatusLabel.text = "주변 기기 스캔 중..."
        } else {
            connectionStatusLabel.text = "블루투스를 켜주세요!"
        }
    }
    
    func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
        discoveredPeripheral = peripheral
        peripheral.delegate = self
        centralManager.connect(peripheral, options: nil)
        centralManager.stopScan()
        connectionStatusLabel.text = "기기 발견! 연결 중..."
    }
    
    func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
        connectionStatusLabel.text = "연결됨: \(peripheral.name ?? "알 수 없는 기기")"
        peripheral.discoverServices([serviceUUID])
        sendButton.isEnabled = true
    }
    
    func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) {
        connectionStatusLabel.text = "연결 실패! 다시 시도 중..."
        centralManager.scanForPeripherals(withServices: [serviceUUID], options: nil)
    }
    
    func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) {
        connectionStatusLabel.text = "연결 끊김! 다시 연결 중..."
        centralManager.connect(peripheral, options: nil)
        sendButton.isEnabled = false
    }
}

// 페리퍼럴 델리게이트
extension ChatViewController: CBPeripheralDelegate {
    
    func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
        guard error == nil else { return }
        
        for service in peripheral.services ?? [] {
            if service.uuid == serviceUUID {
                peripheral.discoverCharacteristics([characteristicUUID], for: service)
            }
        }
    }
    
    func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
        guard error == nil else { return }
        
        for characteristic in service.characteristics ?? [] {
            if characteristic.uuid == characteristicUUID {
                transferCharacteristic = characteristic
                
                // 알림 구독
                if characteristic.properties.contains(.notify) {
                    peripheral.setNotifyValue(true, for: characteristic)
                }
                
                connectionStatusLabel.text = "채팅 준비 완료!"
                sendButton.isEnabled = true
            }
        }
    }
    
    func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
        guard error == nil,
              let data = characteristic.value,
              let message = String(data: data, encoding: .utf8) else { return }
        
        // 메시지 추가
        messages.append((message, false))
        tableView.reloadData()
        scrollToBottom()
    }
}

// 페리퍼럴 매니저 델리게이트
extension ChatViewController: CBPeripheralManagerDelegate {
    
    func peripheralManagerDidUpdateState(_ peripheral: CBPeripheralManager) {
        if peripheral.state == .poweredOn {
            // 서비스 설정
            let transferCharacteristic = CBMutableCharacteristic(
                type: characteristicUUID,
                properties: [.read, .write, .notify],
                value: nil,
                permissions: [.readable, .writeable]
            )
            
            let service = CBMutableService(type: serviceUUID, primary: true)
            service.characteristics = [transferCharacteristic]
            
            peripheralManager.add(service)
            
            // 광고 시작
            peripheralManager.startAdvertising([
                CBAdvertisementDataServiceUUIDsKey: [serviceUUID],
                CBAdvertisementDataLocalNameKey: UIDevice.current.name
            ])
        }
    }
    
    func peripheralManager(_ peripheral: CBPeripheralManager, didReceiveWrite requests: [CBATTRequest]) {
        for request in requests {
            guard let data = request.value,
                  let message = String(data: data, encoding: .utf8) else { continue }
            
            // 메시지 추가
            messages.append((message, false))
            tableView.reloadData()
            scrollToBottom()
            
            // 응답
            peripheralManager.respond(to: request, withResult: .success)
        }
    }
    
    func peripheralManager(_ peripheral: CBPeripheralManager, central: CBCentral, didSubscribeTo characteristic: CBCharacteristic) {
        connectionStatusLabel.text = "상대방이 연결됨!"
        sendButton.isEnabled = true
    }
}

이제 메시지 셀도 만들어볼게요:

class MessageCell: UITableViewCell {
    
    @IBOutlet weak var messageLabel: UILabel!
    @IBOutlet weak var bubbleView: UIView!
    @IBOutlet weak var leadingConstraint: NSLayoutConstraint!
    @IBOutlet weak var trailingConstraint: NSLayoutConstraint!
    
    func configure(with message: String, isMine: Bool) {
        messageLabel.text = message
        
        // 내 메시지와 상대방 메시지 구분
        if isMine {
            bubbleView.backgroundColor = UIColor(red: 0, green: 0.8, blue: 0.4, alpha: 1.0)
            leadingConstraint.constant = 80
            trailingConstraint.constant = 20
        } else {
            bubbleView.backgroundColor = UIColor(red: 0.9, green: 0.9, blue: 0.9, alpha: 1.0)
            leadingConstraint.constant = 20
            trailingConstraint.constant = 80
        }
        
        // 말풍선 모양 설정
        bubbleView.layer.cornerRadius = 16
        bubbleView.clipsToBounds = true
    }
}

이렇게 하면 간단한 블루투스 채팅 앱이 완성돼요! 두 대의 iOS 기기에서 이 앱을 실행하면 서로 메시지를 주고받을 수 있어요. 물론 실제 앱에서는 더 많은 예외 처리와 UI 개선이 필요하겠지만, 기본 개념은 이해하셨을 거예요! 😊

이런 앱 만들어서 재능넷에 올려도 좋을 것 같은데요? ㅋㅋㅋ 블루투스 통신 관련 프로젝트는 수요가 많아서 좋은 포트폴리오가 될 수 있어요! 🚀

7. 블루투스 통신 디버깅 팁 🔍

블루투스 통신은 디버깅이 정말 어려울 수 있어요. 눈에 보이지 않는 무선 통신이니까요! 그래서 몇 가지 꿀팁을 알려드릴게요:

  1. 로그 활용하기: 모든 블루투스 이벤트에 로그를 추가하세요. 특히 상태 변화, 연결/연결 해제, 데이터 송수신 시점에요.
  2. Xcode Bluetooth 디버거: Xcode 11 이상에서는 블루투스 디버깅 도구가 내장되어 있어요. Window > Devices and Simulators > 기기 선택 > Bluetooth 탭에서 확인할 수 있어요.
  3. 패킷 로거 사용: macOS에서 'Additional Tools for Xcode'를 설치하면 패킷 로거 앱을 사용할 수 있어요. 이걸로 블루투스 통신 패킷을 자세히 볼 수 있어요.
  4. 하드웨어 문제 확인: 가끔은 소프트웨어가 아닌 하드웨어 문제일 수도 있어요. 다른 기기로 테스트해보세요.
  5. MTU 크기 고려: 블루투스는 한 번에 전송할 수 있는 데이터 크기에 제한이 있어요. 큰 데이터는 여러 조각으로 나눠서 보내야 할 수도 있어요.

그리고 자주 발생하는 블루투스 통신 문제와 해결책도 알아볼게요:

  1. 연결이 자주 끊김
    - 원인: 거리가 너무 멀거나, 배터리 최적화 설정, 백그라운드 모드 문제
    - 해결: Info.plist에 백그라운드 모드 추가, 연결 끊김 시 자동 재연결 로직 구현
  2. 기기를 찾지 못함
    - 원인: 스캔 타임아웃, 잘못된 서비스 UUID, 블루투스 권한 문제
    - 해결: 스캔 시간 연장, UUID 확인, 권한 설정 확인
  3. 데이터 전송 실패
    - 원인: 특성 속성 불일치, 데이터 형식 오류, MTU 크기 초과
    - 해결: 특성 속성 확인, 데이터 형식 검증, 큰 데이터는 청크로 분할

디버깅할 때 print() 대신 os_log()를 사용하는 것도 좋은 방법이에요. 성능에 미치는 영향이 적고, 로그 레벨을 설정할 수 있거든요:

import os.log

let logger = OSLog(subsystem: "com.yourapp.bluetooth", category: "Connection")

// 일반 로그
os_log("기기 연결 시도 중...", log: logger, type: .info)

// 에러 로그
os_log("연결 실패: %{public}@", log: logger, type: .error, error.localizedDescription)

// 디버그 로그 (개발 중에만 표시)
os_log("특성 값: %{public}@", log: logger, type: .debug, characteristic.value?.hexString ?? "nil")

이런 디버깅 팁들을 활용하면 블루투스 통신 문제를 훨씬 쉽게 해결할 수 있어요! 진짜 블루투스 디버깅은 인내심 싸움이라니까요... ㅋㅋㅋ 🧘‍♂️

8. 블루투스 통신의 보안 고려사항 🔒

블루투스 통신은 무선이기 때문에 보안에 신경을 써야 해요. 특히 민감한 정보를 주고받는 앱이라면 더욱 중요하죠!

블루투스 통신에서 고려해야 할 보안 사항들은 다음과 같아요:

  1. 페어링 및 본딩: 가능하면 기기 간 페어링을 사용하세요. 이는 통신에 암호화 키를 사용하게 해줘요.
  2. 데이터 암호화: 민감한 데이터는 추가로 암호화하세요. Swift에서는 CryptoKit을 사용할 수 있어요.
  3. 인증 메커니즘: 연결된 기기가 정말 우리가 통신하고자 하는 기기인지 확인하는 인증 과정을 구현하세요.
  4. 블루투스 스니핑 방지: 블루투스 통신은 스니핑(도청)될 수 있어요. 중요한 정보는 추가 보안 레이어를 사용하세요.

간단한 데이터 암호화 예제를 살펴볼게요:

import CryptoKit

// 암호화 키 (실제로는 안전하게 저장해야 함)
let symmetricKey = SymmetricKey(size: .bits256)

// 데이터 암호화
func encryptData(_ data: Data) -> Data? {
    do {
        let sealedBox = try AES.GCM.seal(data, using: symmetricKey)
        return sealedBox.combined
    } catch {
        print("암호화 실패: \(error.localizedDescription)")
        return nil
    }
}

// 데이터 복호화
func decryptData(_ encryptedData: Data) -> Data? {
    do {
        let sealedBox = try AES.GCM.SealedBox(combined: encryptedData)
        return try AES.GCM.open(sealedBox, using: symmetricKey)
    } catch {
        print("복호화 실패: \(error.localizedDescription)")
        return nil
    }
}

// 사용 예시
func sendEncryptedMessage(_ message: String, to peripheral: CBPeripheral, characteristic: CBCharacteristic) {
    guard let data = message.data(using: .utf8),
          let encryptedData = encryptData(data) else { return }
    
    peripheral.writeValue(encryptedData, for: characteristic, type: .withResponse)
}

실제 앱에서는 키 관리가 매우 중요해요. 키를 하드코딩하면 안 되고, Keychain이나 Secure Enclave를 사용해서 안전하게 저장해야 해요:

import Security

// Keychain에 키 저장
func saveKeyToKeychain(key: SymmetricKey, identifier: String) -> Bool {
    let keyData = key.withUnsafeBytes { Data($0) }
    
    let query: [String: Any] = [
        kSecClass as String: kSecClassKey,
        kSecAttrApplicationTag as String: identifier.data(using: .utf8)!,
        kSecValueData as String: keyData,
        kSecAttrAccessible as String: kSecAttrAccessibleWhenUnlockedThisDeviceOnly
    ]
    
    // 기존 키 삭제
    SecItemDelete(query as CFDictionary)
    
    // 새 키 저장
    let status = SecItemAdd(query as CFDictionary, nil)
    return status == errSecSuccess
}

// Keychain에서 키 로드
func loadKeyFromKeychain(identifier: String) -> SymmetricKey? {
    let query: [String: Any] = [
        kSecClass as String: kSecClassKey,
        kSecAttrApplicationTag as String: identifier.data(using: .utf8)!,
        kSecReturnData as String: true,
        kSecMatchLimit as String: kSecMatchLimitOne
    ]
    
    var item: CFTypeRef?
    let status = SecItemCopyMatching(query as CFDictionary, &item)
    
    guard status == errSecSuccess,
          let keyData = item as? Data else { return nil }
    
    return SymmetricKey(data: keyData)
}

이런 보안 조치들을 적용하면 블루투스 통신을 훨씬 안전하게 만들 수 있어요. 특히 의료 기기나 금융 관련 앱을 개발한다면 보안은 필수죠! 🛡️

9. 배터리 효율성 최적화하기 🔋

블루투스 통신은 배터리를 많이 소모할 수 있어요. 특히 계속 스캔하거나 데이터를 자주 주고받는 경우에요. 배터리 효율성을 높이는 몇 가지 팁을 알려드릴게요:

  1. 스캔 간격 조절: 계속 스캔하지 말고, 필요할 때만 짧게 스캔하세요.
  2. 스캔 옵션 최적화: 필요한 서비스 UUID만 스캔하고, 신호 강도 필터링을 사용하세요.
  3. 연결 파라미터 조정: 연결 간격(Connection Interval)을 적절히 설정하세요.
  4. 데이터 배치 처리: 작은 데이터를 여러 번 보내는 것보다 모아서 한 번에 보내는 게 효율적이에요.
  5. 불필요한 알림 구독 해제: 더 이상 필요하지 않은 특성의 알림은 구독 해제하세요.

스캔 옵션을 최적화하는 코드 예시를 볼게요:

// 배터리 효율적인 스캔 옵션
func startEfficientScanning() {
    let scanOptions: [String: Any] = [
        // 중복 결과 필터링 (같은 기기를 여러 번 발견하지 않음)
        CBCentralManagerScanOptionAllowDuplicatesKey: false,
        
        // 신호 강도가 특정 값 이상인 기기만 발견 (가까운 기기만)
        CBCentralManagerScanOptionSolicitedServiceUUIDsKey: [serviceUUID]
    ]
    
    centralManager.scanForPeripherals(withServices: [serviceUUID], options: scanOptions)
    
    // 3초만 스캔 후 중지
    DispatchQueue.main.asyncAfter(deadline: .now() + 3.0) {
        self.centralManager.stopScan()
    }
    
    // 30초 후 다시 스캔
    DispatchQueue.main.asyncAfter(deadline: .now() + 30.0) {
        self.startEfficientScanning()
    }
}

연결 파라미터를 조정하는 코드 예시도 볼게요:

// 연결 파라미터 설정 (iOS 11 이상)
func setConnectionParameters(for peripheral: CBPeripheral) {
    if #available(iOS 11.0, *) {
        // 더 긴 연결 간격 설정 (배터리 절약)
        // 간격 범위: 30ms ~ 3s (값: 24 ~ 3200)
        peripheral.setPreferredConnectionLatency(.low, for: .peripheral)
    }
}

이런 최적화를 적용하면 블루투스 통신을 사용하면서도 배터리 소모를 크게 줄일 수 있어요. 사용자 경험에 직접적인 영향을 주는 부분이니 꼭 신경써야 해요! 🔋

10. 실제 프로젝트에 적용하기 🚀

지금까지 배운 내용을 실제 프로젝트에 어떻게 적용할 수 있을지 몇 가지 아이디어를 공유할게요:

  1. 스마트 홈 컨트롤러: 블루투스 스마트 전구, 스위치 등을 제어하는 앱
  2. 피트니스 트래커: 심박수 모니터, 활동 트래커와 연동하는 앱
  3. 모바일 결제 시스템: 블루투스를 통한 근거리 결제 시스템
  4. 위치 기반 서비스: 비콘을 활용한 실내 위치 추적 앱
  5. 파일 공유 앱: 근처 기기와 파일을 공유하는 앱

이런 프로젝트를 진행할 때 아키텍처 패턴을 잘 적용하는 것도 중요해요. 블루투스 관련 코드를 별도의 매니저 클래스로 분리하는 것이 좋아요:

// 블루투스 매니저 클래스
class BluetoothManager: NSObject {
    
    // 싱글톤 인스턴스
    static let shared = BluetoothManager()
    
    // 블루투스 상태 변경 알림을 위한 클로저
    var onStateChanged: ((CBManagerState) -> Void)?
    
    // 기기 발견 알림을 위한 클로저
    var onDeviceDiscovered: ((CBPeripheral, [String: Any], NSNumber) -> Void)?
    
    // 기기 연결 알림을 위한 클로저
    var onDeviceConnected: ((CBPeripheral) -> Void)?
    
    // 데이터 수신 알림을 위한 클로저
    var onDataReceived: ((Data, CBCharacteristic) -> Void)?
    
    // 블루투스 매니저
    private var centralManager: CBCentralManager!
    
    // 현재 연결된 기기
    private(set) var connectedPeripheral: CBPeripheral?
    
    // 타겟 서비스 UUID
    private let serviceUUID: CBUUID
    
    // 타겟 특성 UUID
    private let characteristicUUID: CBUUID
    
    // 초기화
    private override init() {
        serviceUUID = CBUUID(string: "YOUR_SERVICE_UUID")
        characteristicUUID = CBUUID(string: "YOUR_CHARACTERISTIC_UUID")
        super.init()
        centralManager = CBCentralManager(delegate: self, queue: nil)
    }
    
    // 스캔 시작
    func startScanning() {
        if centralManager.state == .poweredOn {
            centralManager.scanForPeripherals(withServices: [serviceUUID], options: nil)
        }
    }
    
    // 스캔 중지
    func stopScanning() {
        centralManager.stopScan()
    }
    
    // 기기 연결
    func connect(to peripheral: CBPeripheral) {
        connectedPeripheral = peripheral
        peripheral.delegate = self
        centralManager.connect(peripheral, options: nil)
    }
    
    // 연결 해제
    func disconnect() {
        if let peripheral = connectedPeripheral {
            centralManager.cancelPeripheralConnection(peripheral)
        }
    }
    
    // 데이터 전송
    func sendData(_ data: Data, to characteristic: CBCharacteristic) {
        guard let peripheral = connectedPeripheral else { return }
        
        if characteristic.properties.contains(.write) {
            peripheral.writeValue(data, for: characteristic, type: .withResponse)
        } else if characteristic.properties.contains(.writeWithoutResponse) {
            peripheral.writeValue(data, for: characteristic, type: .withoutResponse)
        }
    }
}

그리고 델리게이트 구현도 추가해야 해요:

// 센트럴 매니저 델리게이트
extension BluetoothManager: CBCentralManagerDelegate {
    
    func centralManagerDidUpdateState(_ central: CBCentralManager) {
        onStateChanged?(central.state)
        
        if central.state == .poweredOn {
            startScanning()
        }
    }
    
    func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
        onDeviceDiscovered?(peripheral, advertisementData, RSSI)
    }
    
    func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
        onDeviceConnected?(peripheral)
        peripheral.discoverServices([serviceUUID])
    }
    
    func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) {
        print("연결 실패: \(error?.localizedDescription ?? "알 수 없는 오류")")
    }
    
    func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) {
        connectedPeripheral = nil
        print("연결 해제: \(error?.localizedDescription ?? "사용자에 의한 해제")")
    }
}

// 페리퍼럴 델리게이트
extension BluetoothManager: CBPeripheralDelegate {
    
    func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
        guard error == nil else { return }
        
        for service in peripheral.services ?? [] {
            if service.uuid == serviceUUID {
                peripheral.discoverCharacteristics([characteristicUUID], for: service)
            }
        }
    }
    
    func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
        guard error == nil else { return }
        
        for characteristic in service.characteristics ?? [] {
            if characteristic.uuid == characteristicUUID {
                if characteristic.properties.contains(.notify) {
                    peripheral.setNotifyValue(true, for: characteristic)
                }
                
                if characteristic.properties.contains(.read) {
                    peripheral.readValue(for: characteristic)
                }
            }
        }
    }
    
    func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
        guard error == nil, let data = characteristic.value else { return }
        onDataReceived?(data, characteristic)
    }
}

이 매니저 클래스를 사용하면 뷰 컨트롤러에서 블루투스 로직을 깔끔하게 분리할 수 있어요:

class DeviceViewController: UIViewController {
    
    @IBOutlet weak var statusLabel: UILabel!
    @IBOutlet weak var dataLabel: UILabel!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupBluetoothManager()
    }
    
    func setupBluetoothManager() {
        let manager = BluetoothManager.shared
        
        // 블루투스 상태 변경 처리
        manager.onStateChanged = { [weak self] state in
            DispatchQueue.main.async {
                switch state {
                case .poweredOn:
                    self?.statusLabel.text = "블루투스 켜짐"
                case .poweredOff:
                    self?.statusLabel.text = "블루투스 꺼짐"
                default:
                    self?.statusLabel.text = "블루투스 사용 불가"
                }
            }
        }
        
        // 기기 발견 처리
        manager.onDeviceDiscovered = { [weak self] peripheral, _, _ in
            DispatchQueue.main.async {
                self?.statusLabel.text = "기기 발견: \(peripheral.name ?? "알 수 없음")"
                
                // 자동 연결 (실제로는 사용자 확인 후 연결하는 것이 좋음)
                manager.connect(to: peripheral)
            }
        }
        
        // 기기 연결 처리
        manager.onDeviceConnected = { [weak self] peripheral in
            DispatchQueue.main.async {
                self?.statusLabel.text = "연결됨: \(peripheral.name ?? "알 수 없음")"
            }
        }
        
        // 데이터 수신 처리
        manager.onDataReceived = { [weak self] data, _ in
            if let string = String(data: data, encoding: .utf8) {
                DispatchQueue.main.async {
                    self?.dataLabel.text = "받은 데이터: \(string)"
                }
            }
        }
    }
    
    @IBAction func sendButtonTapped(_ sender: UIButton) {
        // 데이터 전송 예시
        if let characteristic = /* 특성 참조 얻기 */, 
           let data = "안녕하세요!".data(using: .utf8) {
            BluetoothManager.shared.sendData(data, to: characteristic)
        }
    }
}

이런 식으로 블루투스 로직을 분리하면 코드가 훨씬 깔끔해지고 유지보수도 쉬워져요. 실제 프로젝트에서는 이런 아키텍처 패턴을 적용하는 것이 좋아요! 👨‍💻

마무리: 블루투스 통신의 미래 🔮

지금까지 Swift로 블루투스 통신을 구현하는 방법에 대해 알아봤어요. 처음에는 어려워 보일 수 있지만, 기본 개념만 이해하면 생각보다 쉽게 구현할 수 있죠! ㅋㅋㅋ

블루투스 기술은 계속 발전하고 있어요. 블루투스 5.0부터는 전송 속도와 범위가 크게 향상되었고, 최신 버전에서는 더 많은 기능들이 추가되고 있어요. 특히 저전력 블루투스(BLE)는 IoT 기기와의 통신에 매우 중요한 역할을 하고 있죠.

앞으로 웨어러블 기기와 스마트홈 기기가 더 많아질수록, 블루투스 통신 기술은 더욱 중요해질 거예요. 이런 기술을 미리 익혀두면 나중에 큰 도움이 될 거예요! 😊

블루투스 통신 관련 프로젝트를 진행하게 된다면, 재능넷 같은 플랫폼에서 관련 전문가를 찾아보는 것도 좋은 방법이에요. 경험 많은 개발자의 도움을 받으면 훨씬 빠르게 문제를 해결할 수 있으니까요! 🚀

여러분도 이제 Swift로 블루투스 통신을 구현할 준비가 되었나요? 오늘 배운 내용을 바탕으로 멋진 앱을 만들어보세요! 화이팅! 💪

댓글 작성

이 글에 대한 여러분의 생각을 들려주세요

댓글 0
댓글을 불러오는 중입니다.

아직 댓글이 없습니다.