外围和中央同时在同一个应用程序iOS11上

时间:2018-01-23 15:51:17

标签: ios swift bluetooth

我正在尝试制作一款可用作蓝牙手表主控的应用程序(例如健身手环,智能手表)。我已经对此进行了研究,尽管有些人设法这样做,但他们没有提供有关该过程的许多细节。以下是我发现的一些“解决方案”:

Is it possible to switch central and peripheral each other on iOS?

Can iOS do central and peripheral work on same app at same time?

Peripheral and central at the same time on iOS

所有这些都在Objective-C中,尽管我对它很熟悉,但这些帖子已有3年多的历史,所以关于代码的事情已经发生了变化。另一个问题是我需要将该应用程序与其他蓝牙设备一起使用,而不是上面提到的iOS设备,目前连接请求只能来自iPhone,而不能来自蓝牙设备。

问题是,是否有可能实现预期的结果,如果是,那么最好的方法是什么?到目前为止,提出的解决方案之一是连接到设备,获取UUID,然后将iPhone切换到外围模式,以便它可以宣传它的服务。这是不可能的(在我看来),至少在目前这个阶段。

iOS已经有一个预定义的服务,当它们中的两个连接时,设备(当前时间服务)可以发现和访问它,而不需要我的任何修改,所以应该有办法实现这一点。

我希望我能够清楚地了解这个问题,如果你相信我可以添加更多细节来澄清背景,请告诉我。谢谢你的时间。

我在发现外围设备的视图中发布了一些关键代码:

 override func viewDidAppear(_ animated: Bool) {

    manager = CBCentralManager(delegate: self, queue: nil)
    peripheralManager = CBPeripheralManager(delegate: self, queue: nil)
    peripherals = []

    if (manager?.state == CBManagerState.poweredOn) {
       scanBLEDevices()
    self.tableView.reloadData()
    }
}
 func peripheralManagerDidUpdateState(_ peripheral: CBPeripheralManager) {
    switch(peripheral.state)
    {
    case.unsupported:
        print("Peripheral is not supported")
    case.unauthorized:
        print("Peripheral is unauthorized")
    case.unknown:
        print("Peripheral is Unknown")
    case.resetting:
        print("Peripheral is Resetting")
    case.poweredOff:
        print("Peripheral service is powered off")
    case.poweredOn:
        print("Peripheral service is powered on")
        print("Start advertising.")

        let serviceUUID:CBUUID = CBUUID(string: self.service_uuid_string)
        let locationUUID:CBUUID = CBUUID(string: self.location_and_speed)

        // Start with the CBMutableCharacteristic
        self.locationCharacteristic = CBMutableCharacteristic(type: locationUUID, properties: .notify , value: nil, permissions: .readable)

        // Then the service
        let locationService = CBMutableService(type: serviceUUID, primary: true)

        // Add the characteristic to the service
        locationService.characteristics?.append(locationCharacteristic!)

        // And add it to the peripheral manager
        self.peripheralManager?.add(locationService)
        peripheralManager?.startAdvertising([CBAdvertisementDataServiceUUIDsKey : serviceUUID])
    }

}

1 个答案:

答案 0 :(得分:0)

我正在找回实现所需功能的正确方法。在初始化peripheralManager之后,创建一个CBMutableService并保持对它的引用(在类的顶部声明)。

3600

下一步是检查外围设备管理器状态,并在收到poweredOn状态后执行所有必需的工作:

var globalService:CBMutableService? = nil