CoreBluetooth peripheral.name总是为零

时间:2015-10-05 04:37:18

标签: ios swift bluetooth swift2 core-bluetooth

我只想获得附近蓝牙设备名称的列表。但是,peripheral.name始终为零。广告包中的名称也始终为零。我附近有7台设备。我可以看到他们而不是他们的名字。

我正在使用Swift2.0和XCode7。

我的代码如下(我还添加了CoreBluetooth.framework):

import UIKit
import CoreBluetooth

class ViewController: UIViewController, CBCentralManagerDelegate {

    var centralManager: CBCentralManager!
    var blueToothReady = false

    override func viewDidLoad() {
        super.viewDidLoad()
        startUpCentralManager()
    }

    func startUpCentralManager() {
        print("Initializing central manager")
        centralManager = CBCentralManager(delegate: self, queue: nil)
    }

    func discoverDevices() {
        print("discovering devices")
        centralManager.scanForPeripheralsWithServices(nil, options: nil)
        // centralManager.scanForPeripheralsWithServices(nil, options: [CBCentralManagerScanOptionAllowDuplicatesKey : NSNumber(bool: true)])

    }

    func centralManager(central: CBCentralManager, didDiscoverPeripheral peripheral: CBPeripheral, advertisementData: [String : AnyObject], RSSI: NSNumber) {
        let nameOfDeviceFound = (advertisementData as NSDictionary).objectForKey(CBAdvertisementDataLocalNameKey) as? NSString
        print("\(nameOfDeviceFound)")
        print("Discovered \(peripheral.name)")
    }


    func centralManager(central: CBCentralManager, didConnectPeripheral peripheral: CBPeripheral) {
        print("Connected to a peripheral")
    }


    func centralManager(central: CBCentralManager, didFailToConnectPeripheral peripheral: CBPeripheral, error: NSError?) {
        print("Failed to connect to peripheral")
    }

    func centralManager(central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: NSError?) {
        print("Disconnected from Peripheral")
    }

    func centralManager(central: CBCentralManager, willRestoreState dict: [String : AnyObject]) {
        print("Will restore state")
    }

    func centralManagerDidUpdateState(central: CBCentralManager) {
        print("checking state")
        switch (central.state) {
        case .PoweredOff:
            print("CoreBluetooth BLE hardware is powered off")

        case .PoweredOn:
            print("CoreBluetooth BLE hardware is powered on and ready")
            blueToothReady = true;

        case .Resetting:
            print("CoreBluetooth BLE hardware is resetting")

        case .Unauthorized:
            print("CoreBluetooth BLE state is unauthorized")

        case .Unknown:
            print("CoreBluetooth BLE state is unknown");

        case .Unsupported:
            print("CoreBluetooth BLE hardware is unsupported on this platform");

        }
        if blueToothReady {
            discoverDevices()
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

提前致谢。

0 个答案:

没有答案