본문 바로가기
프로그래밍/iOS-Swift

[SWIFT] CoreBluetooth 예제

by 채연2 2021. 4. 6.

import UIKit
import CoreBluetooth

class ViewController: UIViewController {
    
    @IBOutlet weak var tblOfList: UITableView!
    @IBOutlet weak var btnOfScan: UIButton!
    @IBOutlet weak var lblOfDeviceName: UILabel!
    
    var peripherals:[CBPeripheral] = []
    var centralManager: CBCentralManager!
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.tblOfList.tableFooterView = UIView()
        centralManager = CBCentralManager(delegate: self, queue: .main)
        
    }
    
    @IBAction func btnScanClick( sender: Any) {
        print("scan Start")
        if(!centralManager.isScanning) {
            centralManager?.scanForPeripherals(withServices: nil, options: nil)
        }
        DispatchQueue.main.asyncAfter(deadline: .now() + 60.0) {
            self.centralManager.stopScan()
            print("Scanning stop")
        }
    }
}
extension ViewController : UITableViewDelegate,UITableViewDataSource {
    func tableView( _ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return peripherals.count
    }
    
    func tableView( _ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = self.tblOfList.dequeueReusableCell(withIdentifier: "listCell", for: indexPath)
        let peripheral = peripherals[indexPath.row]
        cell.textLabel?.text = peripheral.name
        return cell
    }
    func tableView( _ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let peripheral = peripherals[indexPath.row]
        print("Details : ", peripheral)
    }
}
extension ViewController : CBPeripheralDelegate, CBCentralManagerDelegate{
    func centralManager( _ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
        if !(peripheral.name ?? "").isEmpty {
            var check:Bool = false
            for p in peripherals {
                if(p.name == peripheral.name) {
                    check = true
                }
            }
            
            if(!check) {
            self.peripherals.append(peripheral)
            print("Discovered \(peripheral.name ?? "")")
            self.tblOfList.reloadData()
            }
        }
    }
    func centralManagerDidUpdateState( _ central: CBCentralManager) {
        switch central.state {
        case .unknown:
            print("central.state is .unknown")
        case .resetting:
            print("central.state is .resetting")
        case .unsupported:
            print("central.state is .unsupported")
        case .unauthorized:
            print("central.state is .unauthorized")
        case .poweredOff:
            print("central.state is .poweredOff")
        case .poweredOn:
            print("central.state is .poweredOn")
        @unknown default:
            fatalError()
        }
    }
    func centralManager( central: CBCentralManager, didConnect peripheral: CBPeripheral) {
        print("Connected to "+peripheral.name!)
    }
    
    func centralManager( _ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) {
        print(error!)
    }
}
320x100

댓글