如何在Swift中使用iPhone连接的蓝牙?

时间:2016-11-23 11:12:03

标签: ios swift swift2 ios-bluetooth

我需要为我的应用程序使用蓝牙。我只想使用我的iPhone连接的蓝牙。我找到了蓝牙的代号:

///bluetooth scan for devices
func centralManagerDidUpdateState(central: CBCentralManager) {
    if central.state == .PoweredOn {
        central.scanForPeripheralsWithServices(nil, options: nil)
    } else {
        print("Bluetooth not available.")
    }
}

///bluetooth connect to a device
func centralManager(
    central: CBCentralManager,
    didDiscoverPeripheral peripheral: CBPeripheral,
                          advertisementData: [String : AnyObject],
                          RSSI: NSNumber) {
    print("--didDiscoverPeripheral-")

    print(peripheral.name)

    //central.scanForPeripheralsWithServices(nil, options: nil)
    /*let device = (advertisementData as NSDictionary)
        .objectForKey(CBAdvertisementDataLocalNameKey)
        as? NSString

    if device?.containsString(self.BEAN_NAME!) == true {
        self.manager.stopScan()

        self.peripheral = peripheral
        self.peripheral.delegate = self

        manager.connectPeripheral(peripheral, options: nil)
    }*/
}

///bluetooth get services
func centralManager(
    central: CBCentralManager,
    didConnectPeripheral peripheral: CBPeripheral) {
    peripheral.discoverServices(nil)
}

///bluetooth get characteristics
func peripheral(
    peripheral: CBPeripheral,
    didDiscoverServices error: NSError?) {
    for service in peripheral.services! {
        let thisService = service as CBService

        if service.UUID == BEAN_SERVICE_UUID {
            peripheral.discoverCharacteristics(
                nil,
                forService: thisService
            )
        }
    }
}

///bluetooth setup notifications
func peripheral(
    peripheral: CBPeripheral,
    didDiscoverCharacteristicsForService service: CBService,
                                         error: NSError?) {
    for characteristic in service.characteristics! {
        let thisCharacteristic = characteristic as CBCharacteristic

        if thisCharacteristic.UUID == BEAN_SCRATCH_UUID {
            self.peripheral.setNotifyValue(
                true, 
                forCharacteristic: thisCharacteristic
            )
        }
    }
}

///bluetooth changes are coming
func peripheral(
    peripheral: CBPeripheral,
    didUpdateValueForCharacteristic characteristic: CBCharacteristic,
                                    error: NSError?) {
    var count:UInt32 = 0;

    if characteristic.UUID == BEAN_SCRATCH_UUID {
        characteristic.value!.getBytes(&count, length: sizeof(UInt32))

    }
}

///bluetooth disconnect and try again
func centralManager(
    central: CBCentralManager,
    didDisconnectPeripheral peripheral: CBPeripheral,
                            error: NSError?) {
    central.scanForPeripheralsWithServices(nil, options: nil)
}

这段代码扫描蓝牙,但我想我不需要扫描蓝牙。如何使用iPhone已连接的蓝牙?

非常感谢。

0 个答案:

没有答案