如何跨视图控制器访问蓝牙数据?在xcode中

时间:2017-04-12 08:26:48

标签: ios bluetooth core-bluetooth

我正试图通过BLE访问运动传感器(IMU传感器)。结构是在一个视图控制器中连接/配对传感器并修改其设置,然后在另一个视图控制器中访问和分析其输出数据(它们不是segue连接的)。

如何继续访问已在另一个视图控制器中连接的传感器的数据? Coredata不是理想的,因为它是实时呈现并且不需要原始数据来记录。我不能通过segue传递数据,因为它们不是segue连接的(它们可以通过不同的标签栏视图控制器访问)。

我发现一个链接说可以将CBCentralManager等放入AppDelegate,然后它就变成了一个中央管理器属性(How to continue BLE activities onto next view controller)。这是正确的方法吗?如果是这样,中央经理的哪一部分应该放入AppDelegate?

这是我的代码,包括搜索和构建蓝牙连接。

var cManager = CBCentralManager()
var peripheralManager = CBPeripheralManager()

func centralManagerDidUpdateState(central: CBCentralManager!) {

    var message: String = ""
    switch cManager.state {

    case .PoweredOff:
        println("CoreBluetooth BLE hardware is powered off")

        let alertView = UIAlertController(title: "", message: "Please enable Bluetooth to start the measurement", preferredStyle: .Alert)
        alertView.addAction(UIAlertAction(title: "OK", style: .Cancel, handler: nil))
        presentViewController(alertView, animated: true, completion: nil)

        break
    case .PoweredOn:
        println("CoreBluetooth BLE hardware is powered on and ready")

        self.scanForWAX9(self)
        break
    case .Resetting:
        println("CoreBluetooth BLE hardware is resetting")
        break
    case .Unauthorized:
        println("CoreBluetooth BLE state is unauthorized")
        break
    case .Unknown:
        println("CoreBluetooth BLE state is unknown")
        break
    case .Unsupported:
        println("CoreBluetooth BLE hardware is unsupported on this platform")
        break
    default:
        break
    }

}

func centralManager(central: CBCentralManager!, didDiscoverPeripheral peripheral: CBPeripheral!, advertisementData: [NSObject : AnyObject]!, RSSI: NSNumber!) {

    println(peripheral.name);


    //************************************************************************************
    // Add some specification for bluetooth device
    //************************************************************************************

    if (peripheral.name != nil ) && (peripheral.name.rangeOfString("WAX9") != nil) {

        central.connectPeripheral(peripheral, options: nil)

        self.connectedPeripheral = peripheral

        println("PERIPHERAL NAME: \(peripheral.name)\n AdvertisementData: \(advertisementData)\n RSSI: \(RSSI)\n")

        println("UUID DESCRIPTION: \(peripheral.identifier.UUIDString)\n")

        println("IDENTIFIER: \(peripheral.identifier)\n")

        cManager.stopScan()
    }
}

@IBOutlet var connectNotice: UILabel!



func centralManager(central: CBCentralManager!, didConnectPeripheral peripheral: CBPeripheral!) {

    peripheral.delegate = self
    peripheral.discoverServices(nil)

    // self.connectedPeripheral = peripheral

    connectNotice.text = "\(peripheral.name) connected."
    connectNotice.textColor = UIColor.whiteColor()
    connectNotice.backgroundColor = UIColor(red:0.03, green:0.37, blue:0.5, alpha:0.5)

    cManager.stopScan()
    println("Scanning stopped")
    println("Connected to peripheral")
}



// Alert message when fail to connect, e.g. when sensor goes out of range
func centralManager(central: CBCentralManager!, didFailToConnectPeripheral peripheral: CBPeripheral!, error: NSError!) {
    println("FAILED TO CONNECT \(error)")

    let alertView = UIAlertController(title: "", message: "Failed to connect.", preferredStyle: .Alert)
    alertView.addAction(UIAlertAction(title: "OK", style: .Cancel, handler: nil))
    presentViewController(alertView, animated: true, completion: nil)

    self.disconnect()
}

// Start to scan for sensor when disconnected
func centralManager(central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: NSError?) {


    println("Disconnected from peropheral")
    let alertView = UIAlertController(title: "", message: "The connection is stopped.", preferredStyle: .Alert)
    alertView.addAction(UIAlertAction(title: "OK", style: .Cancel, handler: nil))
    presentViewController(alertView, animated: true, completion: nil)

    self.connectedPeripheral = nil
    if scanAfterDisconnecting {
        scanForWAX9(self)
    }

}


func peripheralManagerDidUpdateState(peripheral: CBPeripheralManager!) {

    switch peripheralManager.state {

    case .PoweredOff:
        println("Peripheral - CoreBluetooth BLE hardware is powered off")
        break

    case .PoweredOn:
        println("Peripheral - CoreBluetooth BLE hardware is powered on and ready")
        break

    case .Resetting:
        println("Peripheral - CoreBluetooth BLE hardware is resetting")
        break

    case .Unauthorized:
        println("Peripheral - CoreBluetooth BLE state is unauthorized")
        break

    case .Unknown:
        println("Peripheral - CoreBluetooth BLE state is unknown")
        break

    case .Unsupported:
        println("Peripheral - CoreBluetooth BLE hardware is unsupported on this platform")
        break
    default:
        break
    }

}

func peripheral(peripheral: CBPeripheral!, didDiscoverServices error: NSError!) {

    if (error != nil) {
        println("ERROR: \(error)")
        disconnect()
        return
    }

    for service in peripheral.services
    {
        NSLog("Discovered service: \(service.UUID)")

        peripheral.discoverCharacteristics(nil, forService: service as CBService)

    }
}

1 个答案:

答案 0 :(得分:2)

您可以创建一个全局类,它可以成为中央管理器属性吗?

请参阅此答案如何执行此操作:https://stackoverflow.com/a/6067515/1331332

然后,您可以使用NSNotificationCenter在整个应用中发送数据,只需在每个 ViewController中设置观察者