为什么我的特征不会出现在BLE广告Swift中

时间:2015-12-14 11:12:44

标签: iphone swift core-bluetooth bluetooth-lowenergy

我想宣传iPhone作为外围设备的一些特性,但是虽然该服务似乎包含了用BLE扫描仪查看它们时不会显示的特性,但该服务运行良好并且显示localNameKey。

感谢

import UIKit
import CoreBluetooth

class ViewController: UIViewController, CBPeripheralManagerDelegate{

var peripheralManager: CBPeripheralManager!
let myCustomServiceUUID: CBUUID = CBUUID(string: "B5893BC9-63AB-42A5-BB33-EEAE686BED1D")
let myCustomCharacteristic: CBUUID = CBUUID(string: "9BA41369-C5B7-456B-B4E3-BB0A8DFF3A95")
let myCustomCharacteristic2: CBUUID = CBUUID(string: "9BA41369-C5B7-456B-B4E3-BB0A8DFF3A85")
var myService: CBMutableService!
var myCharacteristics: CBMutableCharacteristic!
var myCharacteristics2: CBMutableCharacteristic!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    peripheralManager = CBPeripheralManager(delegate: self, queue: nil)
    myService = CBMutableService(type: myCustomServiceUUID, primary: true)

    myCharacteristics = CBMutableCharacteristic(type: myCustomCharacteristic, properties: CBCharacteristicProperties.Broadcast, value: nil, permissions: CBAttributePermissions.Readable)
    myCharacteristics2 = CBMutableCharacteristic(type: myCustomCharacteristic2, properties: CBCharacteristicProperties.Broadcast, value: nil, permissions: CBAttributePermissions.Readable)

    myService.characteristics = [myCharacteristics, myCharacteristics2]
    peripheralManager.addService(myService)



}

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

func peripheralManagerDidUpdateState(peripheral: CBPeripheralManager) {
    if peripheral.state == CBPeripheralManagerState.PoweredOn {
        let dataTobeAdvetised :[String: AnyObject!] = [CBAdvertisementDataServiceUUIDsKey: [myService.UUID], CBAdvertisementDataLocalNameKey: "MY Device"]
        self.peripheralManager.startAdvertising(dataTobeAdvetised)
        print(myService)
        print("It should be working!........")


    } else if peripheral.state == CBPeripheralManagerState.PoweredOff {
        self.peripheralManager.stopAdvertising()
    }
}



}

2 个答案:

答案 0 :(得分:0)

您不得使用CBCharacteristic.broadcast属性值。

来自documentation -

  
      
  • CBCharacteristicPropertyBroadcast
  •   
     

可以使用特征来广播特征的值   配置描述符。

     

此属性不允许通过发布的本地特征   CBPeripheralManager类的addService:方法。这意味着   初始化新的时不能使用此属性   CBMutableCharacteristic对象通过   initWithType:properties:value:permissions:方法   CBMutableCharacteristic类。

根据您的要求,您应该使用CBCharacteristicPropertyReadCBCharacteristicPropertyWriteWithoutResponseCBCharacteristicPropertyWrite的某种组合。

答案 1 :(得分:0)

老问题,但希望这会有助于其他人。我正在努力解决同样的问题,但对我来说没有didAddService回调。结果是GATT初始化应该在外围状态变为PoweredOn之后。

func peripheralManagerDidUpdateState(peripheral: CBPeripheralManager) {
    if peripheral.state == CBPeripheralManagerState.PoweredOn {
        //Do initialisation and then start advertising.
    }
}