在這篇文章中,我們將繼續進行藍牙應用程式的開發,今天的重點是設置主畫面(MainViewController)。透過主畫面,我們將顯示藍牙裝置列表,並且能夠點擊連接裝置,取得光線數據。接下來,我們會一步步分析代碼,了解如何透過 CoreBluetooth 來處理藍牙連線與顯示。
這是 MainViewController.swift 文件的基本結構:
//
//  MainViewController.swift
//  Bluetooth
//
//  Created by imac-2627 on 2024/9/18.
//
import UIKit
import CoreBluetooth
MainViewController 是一個 UIViewController,負責管理藍牙裝置的顯示與數據更新。以下是這個類的主要屬性:
class MainViewController: UIViewController {
    
    // MARK: - IBOutlet
    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var lbLightNumber: UILabel!
    
    // MARK: - Property
    private var peripherals: [CBPeripheral] = []
    private var connectedPeripheral: CBPeripheral?
    
    // MARK: - LifeCycle
    override func viewDidLoad() {
        super.viewDidLoad()
        setUI()
        BluetoothService.shared.delegate = self
    }
}
tableView: 顯示可連接的藍牙設備列表。lbLightNumber: 顯示接收到的光線數據。peripherals: 用來存放掃描到的藍牙設備。connectedPeripheral: 當前連接的藍牙設備。在 viewDidLoad() 中,我們調用 setUI() 方法來設置主畫面的介面元素,同時將 BluetoothService.shared.delegate 設定為當前控制器,這樣就可以接收藍牙服務的更新。
override func viewDidLoad() {
    super.viewDidLoad()
    setUI()
    BluetoothService.shared.delegate = self
}
setUI() 方法負責初始化 tableView 的委派和數據源,並設置初始的光線數據顯示:
func setUI() {
    tableView.delegate = self
    tableView.dataSource = self
    tableView.register(UITableViewCell.self, forCellReuseIdentifier: "BluetoothCell")
    lbLightNumber.text = "等待數據..."
}
在這裡,我們使用兩個擴展來處理藍牙設備的掃描與顯示,以及藍牙數據的接收與更新。
透過遵循 BluetoothServiceDelegate 和 CBPeripheralDelegate,我們能夠接收藍牙設備的掃描結果和數據:
extension MainViewController: BluetoothServiceDelegate, CBPeripheralDelegate {
    
    func getBLEPeripherals(peripherals: [CBPeripheral]) {
        self.peripherals = peripherals
        DispatchQueue.main.async {
            self.tableView.reloadData()
        }
    }
    
    func getBLEPeripheralsValue(value: String) {
        DispatchQueue.main.async {
            self.lbLightNumber.text = "光線強度:\(value)"
        }
        print("\(value)")
    }
}
當藍牙服務掃描到設備時,getBLEPeripherals(peripherals:) 會更新設備列表;而 getBLEPeripheralsValue(value:) 會更新光線數據的顯示。
使用 UITableViewDelegate 和 UITableViewDataSource,我們可以將掃描到的藍牙設備顯示在列表中,並提供點擊連接的功能:
extension MainViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return peripherals.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "BluetoothCell", for: indexPath)
        let peripheral = peripherals[indexPath.row]
        cell.textLabel?.text = peripheral.name ?? "未知設備"
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let selectedPeripheral = peripherals[indexPath.row]
        BluetoothService.shared.connectPeripheral(peripheral: selectedPeripheral)
    }
}
tableView(_:cellForRowAt:): 這個方法負責將每個藍牙設備顯示為表格中的一行。tableView(_:didSelectRowAt:): 用戶點擊某個設備後,會觸發藍牙連接操作。在這篇文章中,我們實作了主畫面,展示了如何掃描藍牙設備並顯示在 tableView 中,並且實現了點擊設備進行連接的功能。
在這30天內,我複習了所有在暑假學習過的App,也將學的寫成了文章,或許第一次參賽來說,寫得不是那麼好,但是很有趣,讓我透過寫文章的方式去理解我自己在開發App時的整個流程區塊,同時也在無形之間令自己的Coding能力加強。