【iOS/SwiftUI】Bluetoothの通信機能の実装

SwiftUIに戻る

目次

概要

Core Bluetoothというフレームワークを使って、Bluetoothの通信を行う。
このフレームワークを使うことでBlutooth Low Energy(通称「BLE」)を使ったデータ通信が可能になる。

まずはBluetoothでデバイスのデータを取得するところから始めてみよう。

登場人物

用語役割
Central他のデバイスをスキャンし、接続とデータのやりとりを行う。
Peripheralデータを提供するデバイス

ソースコード

下準備

Info.plistに「Bluetooth Always Usage Description」をプロパティに追加し、Bluetoothに接続する際のメッセージを入力する。

実装内容

import CoreBluetooth
import Foundation

class BluetoothManager: NSObject {
    private var centralManager: CBCentralManager
    private var characteristic: CBCharacteristic
    
    override init() {
        self.centralManager = CBCentralManager(delegate: self, queue: nil)
    }
}

extension BluetoothManager: CBCentralManagerDelegate {
    func centralManagerDidUpdateState(_ central: CBCentralManager) {
        switch central.state {
        case .unknown:
            print("Bluetooth is unknown.")
        case .resetting:
            print("Bluetooth is resetting.")
        case .unsupported:
            print("Bluetooth is unsupported.")
        case .unauthorized:
            print("Bluetooth is unauthorized.")
        case .poweredOff:
            print("Bluetooth is powered off.")
        case .poweredOn:
            print("Bluetooth is powered on.")
        }
    }
    
    func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
        print("Peripheralデバイスを発見: \(peripheral.name) RSSI: \(RSSI)")
        centralManager.connect(peripheral, options: nil)
    }
    
    func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
        print("Peripheralデバイスに接続しました: \(peripheral.name)")
        peripheral.delegate = self
        peripheral.discoverServices(nil)
    }
    
    func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: (any Error)?) {
        print("Peripheralデバイスへの接続に失敗しました: \(error?.localizedDescription ?? "不明なエラー")")
    }
}

詳細

ペリフェラルを検出した場合はcentralManagerDidUpdateStateメソッドが呼び出される。
そして、検出した時のステータスに応じて分岐することができる。

メソッド名内容
centralManagerDidUpdateState(_ central: CBCentralManager)ペリフェルのステータスが更新された時に呼ばれる。
電源がONになってる時などに呼ばれる。
centralManager(_ central: CBCentralManager,
didDiscover peripheral: CBPeripheral,
advertisementData: [String : Any],
rssi RSSI: NSNumber)
ペリフェルが発見された時に呼ばれる。
centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral)ペリフェルに接続できた時に呼ばれる。
centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: (any Error)?)ペリフェルに接続時にエラーが発生した時に呼ばれる。

まずはこの辺りで

参考ページ

SwiftUIに戻る