【发布时间】:2019-07-22 20:20:01
【问题描述】:
我正在开发一个尝试连接到 nrf52840 开发工具包的 iOS 应用程序。当我在一个场景上连接它时它连接没问题,调试菜单告诉我它连接,当我移动到另一个场景时它断开连接。
我尝试将连接移动到代码的不同区域,但这并没有改变任何东西。
import UIKit
import CoreBluetooth
class ViewController: UIViewController, CBCentralManagerDelegate {
private var centralManager : CBCentralManager!
private var blePeripheral : CBPeripheral!
private var uniqueID : Any!
// manager = CBCentralManager(delegate: self, queue: nil)
override func viewDidLoad() {
super.viewDidLoad()
print("++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++")
// Do any additional setup after loading the view, typically from a nib.
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 10.0) {
print("Connecting to peripheral \(self.peripheral)")
}
if(centralManager != nil){
if isConnectedtoAnything(){
print("not scanning")
print(centralManager.debugDescription)
}else{
print("scanning")
}
}
}
func centralManagerDidUpdateState(_ central: CBCentralManager) {
if central.state == .poweredOn {
print("Bluetooth is On")
centralManager.scanForPeripherals(withServices: nil, options: nil)
} else {
print("Bluetooth is not activate")
}
}
@IBAction func StartSearch() {
print("starting Search")
centralManager = CBCentralManager(delegate: self, queue: nil, options: nil)
}
@IBAction func StopConn() {
if centralManager.isScanning {
print("Do Nothing")
}else{
print("cancelling Connection")
centralManager.cancelPeripheralConnection(blePeripheral)
}
}
public func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
print("\nName : \(peripheral.name ?? "(No name)")")
if peripheral.name == "Device_Name"{
print("Found the Device")
blePeripheral=peripheral
central.connect(blePeripheral, options: nil)
central.stopScan()
if !central.isScanning{
print("===============================")
print("Connected Successfuly")
}
}
print("RSSI : \(RSSI)")
for ad in advertisementData{
print("AD Data: \(ad)")
}
}
func isConnectedtoAnything() ->Bool{
if centralManager.isScanning {
print("It is scanning ")
return false
}
else {
return true
}
}
func peripheral(peripheral: CBPeripheral,
didUpdateValueForCharacteristic characteristic: CBCharacteristic,
error: NSError?)
{
if let error = error {
print("Failed… error: \(error)")
return
}
print("characteristic uuid: \(characteristic.uuid), value: \(characteristic.value)")
}
func centralManager(_ central: CBCentralManager, didDiscoverPeripheral peripheral: CBPeripheral,
advertisementData: [NSObject : AnyObject]!, RSSI: NSNumber!)
{
print("Peripheral : \(peripheral)")
}
我只想让应用保持与开发工具包的连接
【问题讨论】:
-
您可能不想在视图控制器中使用蓝牙委托方法。你需要创建另一个对象来处理你所有的蓝牙东西;创建该对象的单个实例并在视图控制器之间传递它。
标签: swift xcode bluetooth-lowenergy core-bluetooth