[swift] Swift Core Bluetooth와 푸시 알림 통합

Swift Core Bluetooth는 iOS 기기 간에 Bluetooth 통신을 가능하게 해주는 프레임워크입니다. 또한, 푸시 알림은 사용자에게 중요한 알림을 전송하는 데 사용되는 기능입니다. 이번 포스트에서는 Swift Core Bluetooth와 푸시 알림을 통합하는 방법에 대해 알아보겠습니다.

1. Core Bluetooth 설정하기

먼저, Core Bluetooth 프레임워크를 사용하기 위해 프로젝트에 추가해야 합니다. Xcode에서 프로젝트를 열고, 프로젝트 네비게이터에서 프로젝트 파일을 선택한 다음, “Build Phases” 탭으로 이동하여 “Link Binary With Libraries” 항목에 “CoreBluetooth.framework”을 추가합니다.

2. Bluetooth 백그라운드 모드 활성화하기

Bluetooth 통신을 백그라운드에서 유지하기 위해 프로젝트의 “Capabilities” 탭으로 이동한 후, “Background Modes” 항목을 활성화합니다. 그리고 “Uses Bluetooth LE accessories” 및 “Acts as a Bluetooth LE accessory” 옵션을 선택합니다.

3. Peripheral Manager 설정하기

Peripheral Manager는 퍼리프럴 역할을 하는 iOS 기기를 나타내는 클래스입니다. 퍼리프럴 기기로 동작하기 위해 다음과 같이 코드를 작성합니다.

import CoreBluetooth

class BluetoothPeripheral: NSObject, CBPeripheralManagerDelegate {
    var peripheralManager: CBPeripheralManager!
    
    override init() {
        super.init()
        peripheralManager = CBPeripheralManager(delegate: self, queue: nil)
    }
    
    // TODO: Peripheral Manager Delegate Methods
}

위 코드에서는 CBPeripheralManagerDelegate 프로토콜을 채택하고, CBPeripheralManager 객체를 생성하여 delegate를 설정하고 있습니다. 또한, delegate 메서드를 구현할 수 있는 BluetoothPeripheral 클래스를 정의하였습니다.

4. Peripheral Manager Delegate 구현하기

이제 Peripheral Manager의 델리게이트 메서드를 구현하여 퍼리프럴 역할을 정의할 수 있습니다. 예를 들어, 중앙 기기가 연결되었을 때 알림을 보내는 코드는 다음과 같습니다.

import UserNotifications

extension BluetoothPeripheral {
    // 퍼리프럴 기기 상태가 변경되었을 때 호출되는 메서드
    func peripheralManagerDidUpdateState(_ peripheral: CBPeripheralManager) {
        if peripheral.state == .poweredOn {
            // 중앙 기기에 연결 요청 전송
            peripheralManager.startAdvertising([CBAdvertisementDataLocalNameKey: "MyDevice"])
        }
    }
    
    // 중앙 기기가 연결되었을 때 호출되는 메서드
    func peripheralManager(_ peripheral: CBPeripheralManager, central: CBCentral, didSubscribeTo characteristic: CBCharacteristic) {
        // 알림을 생성하고 푸시 알림을 전송
        let content = UNMutableNotificationContent()
        content.title = "Peripheral Notification"
        content.body = "The central device has subscribed to the characteristic"
        
        let request = UNNotificationRequest(identifier: "PeripheralNotification", content: content, trigger: nil)
        UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
    }
}

위 코드는 peripheralManagerDidUpdateState 메서드에서 Peripheral Manager의 상태를 확인하고, Bluetooth가 켜져 있는 경우 중앙 기기에 연결 요청을 전송합니다. 또한, peripheralManager(_:central:didSubscribeTo) 메서드에서 중앙 기기가 연결되었을 때 알림을 생성하고 푸시 알림을 전송하는 코드를 작성합니다.

5. 푸시 알림 설정하기

푸시 알림을 사용하기 위해 프로젝트에 UserNotifications 프레임워크를 추가해야 합니다. 프로젝트 네비게이터에서 “Build Phases” 탭으로 이동하여 “Link Binary With Libraries” 항목에 “UserNotifications.framework”을 추가합니다.

6. 푸시 알림 권한 요청하기

푸시 알림을 사용하기 위해 사용자에게 권한을 요청해야 합니다. AppDelegate.swift 파일에 다음 코드를 추가합니다.

import UserNotifications

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { (granted, error) in
        guard granted else { return }
        DispatchQueue.main.async {
            application.registerForRemoteNotifications()
        }
    }
    return true
}

위 코드는 앱이 시작될 때 UNUserNotificationCenter를 사용하여 푸시 알림 권한을 요청하는 코드입니다.

7. 푸시 알림 처리하기

Remote Notification을 받으면 앱이 백그라운드에서 실행되거나 종료되어 있을 때도 사용자에게 알림을 표시할 수 있습니다. AppDelegate.swift 파일에 다음 코드를 추가합니다.

import UserNotifications

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
    // 푸시 알림 처리 코드 작성
    completionHandler(.newData)
}

위 코드에서는 didReceiveRemoteNotification 메서드에서 푸시 알림을 처리하는 코드를 작성할 수 있습니다.

이제, Swift Core Bluetooth와 푸시 알림을 통합하는 방법에 대해 알아보았습니다. 이를 통해 iOS 기기 간 Bluetooth 통신과 알림 기능을 함께 사용할 수 있습니다.

더 자세한 내용은 Apple Developer Documentation를 참조하세요.