无法使用swift3搜索和显示BLE设备名称

时间:2018-01-02 09:00:31

标签: ios swift3 bluetooth-lowenergy

我正在使用Swift 3为iOS编写BLE测试应用程序,而我正在努力解决无法扫描设备的问题。

我想在最后一个区块调用 "print("devicename: \(peripheral)")" 方法。

import UIKit
import CoreBluetooth

class ViewController: UIViewController, CBCentralManagerDelegate {

    private var isScanning = false
    var centralManager: CBCentralManager!

    override func viewDidLoad() {
        super.viewDidLoad()

        self.centralManager = CBCentralManager(delegate: self,queue: nil)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }


    func centralManagerDidUpdateState(_ central: CBCentralManager) {

        if central.state == CBManagerState.poweredOn {

            centralManager.scanForPeripherals(withServices: nil,options: nil)
        } else {
            print("not ready")
        }
    }

    private func centralManager(central: CBCentralManager!,didDiscoverPeripheral peripheral: CBPeripheral!,advertisementData: [String : AnyObject]!,RSSI: NSNumber!)
    {
        print("devicename: \(peripheral)")
    }
}

1 个答案:

答案 0 :(得分:0)

func centralManagerDidUpdateState(_ central: CBCentralManager){

    switch central.state {

        case .poweredOn:    central.scanForPeripherals(withServices: nil, options: nil)

        default: print("Please turn on bluetooth")
        break
    }

func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber){

     print("----->",advertisementData)
     print("==>", peripheral)
}