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
'프로그래밍 > iOS-Swift' 카테고리의 다른 글
[SWIFT] BMPlayer (0) | 2021.04.07 |
---|---|
[SWIFT] Podfile 작성 (0) | 2021.04.06 |
[SWIFT] Failed to instantiate the default view controller for UIMainStoryboardFile 'Main' - perhaps the designated entry point is not set? (0) | 2021.04.06 |
[SWIFT] DatePicker 생년월일 Wheel Style (0) | 2021.04.05 |
[SWIFT] Camera & Gallery Image Pick (0) | 2021.04.05 |
댓글