我有一个简单的应用程序,我实现了一个可以连接到外围设备并读取或写入他的中心。
由于某些原因,这总是有效,但现在我不知道为什么代理方法 didDiscoverServices 没有被触发。我在 didConnect 方法中调用 peripheral.discoverServices()。当调用discoverServices方法时,我不断收到委托方法未实现或为零的错误。但该方法已实施,我正在寻找存在的服务。
这是我的代码
class SearchForPeripheralsTableViewController: UITableViewController, CBCentralManagerDelegate, CBPeripheralDelegate {
var centralManager: CBCentralManager?
var cbPeripheral: CBPeripheral!
var peripherals: [DiscoveryPeripherals] = []
var listOfServices: [ServiceIdentifier] = []
fileprivate func fillServices(){
listOfServices.append(ServiceIdentifier(CBUUID(string: "FFF0")))
}
override func viewWillAppear(_ animated: Bool) {
tableViewSearchPeripherals.dataSource = self
tableViewSearchPeripherals.delegate = self
initCentralManager()
}
override func viewDidAppear(_ animated: Bool) {
tableViewSearchPeripherals.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
print("Peripheral connected")
let service = listOfServices.first(where: { $0.uuid == CBUUID(string:"FFF0")})
peripheral.discoverServices([(service?.uuid)!])
}
override func viewDidLoad() {
super.viewDidLoad()
fillServices()
}
func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
if error != nil {
print("Error discovering services: \(String(describing: error?.localizedDescription))")
return
}
if let services = peripheral.services {
for service in services {
let characteristics = listOfCharacteristics.map({ (element) -> CBUUID in return element.uuid})
// let characteristic = GetCharacteristicByCBUUID(uuid: CBUUID(string: "FFF1"))
peripheral.discoverCharacteristics(characteristics, for: service)
}
}
}
}
答案 0 :(得分:1)
您必须将对象设置为CBPeripheral
的委托才能调用CBPeripheralDelegate
个函数:
func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
print("Peripheral connected")
peripheral.delegate = self
let service = listOfServices.first(where: { $0.uuid == CBUUID(string:"FFF0")})
peripheral.discoverServices([(service?.uuid)!])
}
答案 1 :(得分:1)
swift 3
func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
peripheral.delegate = self
self.selectPeripheral.discoverServices(nil)
}
func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
if let errorService = error{
print(errorService)
return
}
else if let services = peripheral.services as [CBService]!{
for service in services{
peripheral.discoverCharacteristics(nil, for: service)
}
}
print("==>",peripheral.services!)
}
答案 2 :(得分:-2)
您还需要初始化CBCentralManagera并添加"隐私 - 蓝牙外围设备使用说明" info.plist中的消息
请在Swift 3.0中检查此代码对您有所帮助。 https://github.com/JCGuidi/BLE-iOS-Swift-3.0/blob/master/Project/BluetoothLE/ViewController.swift