我正在尝试在iOS上开始使用蓝牙,以使两个相邻的设备使用CoreBluetooth
进行通信。
根据我的理解,一种设备将必须扮演外围设备的角色,而另一种将扮演中央设备的角色。
我开始编写一个微型应用程序来扮演外围设备的角色。 这是相关代码:
import UIKit
import CoreBluetooth
class ViewController: UIViewController,CBPeripheralManagerDelegate {
let serviceOne_UUID = CBUUID(string:"FB694B90-F49E-4597-8306-171BBA78F846"),
svcOneChrcOne_UUID = CBUUID(string:"EB6727C4-F184-497A-A656-76B0CDAC633A")
var cbPerifMngr:CBPeripheralManager!, mutaSRVC:CBMutableService!,
svcOneCharacOne:CBMutableCharacteristic!
override func viewDidLoad() {
super.viewDidLoad()
cbPerifMngr = CBPeripheralManager(delegate: self, queue: nil)
}
// CBPeripheralManagerDelegate protocol implementation.
func peripheralManagerDidUpdateState(_ peripheral: CBPeripheralManager) {
if peripheral.state == .poweredOn {
mutaSRVC = CBMutableService(type: serviceOne_UUID, primary: true)
svcOneCharacOne = CBMutableCharacteristic(type: svcOneChrcOne_UUID,
properties: .read, value: nil, permissions: .readable)
mutaSRVC.characteristics = [svcOneCharacOne]
cbPerifMngr?.add(mutaSRVC)
}
}
func peripheralManager(_ peripheral: CBPeripheralManager, didAdd service: CBService, error: Error?) {
if error != nil {
print("Error in \(#function) :\n\(error!)")
} else {
cbPerifMngr.startAdvertising([CBAdvertisementDataServiceUUIDsKey:service.uuid])
}
}
func peripheralManagerDidStartAdvertising(_ peripheral: CBPeripheralManager, error: Error?) {
if error != nil {
print("Error in \(#function) :\n\(error!)")
}
}
}
我现在的问题是:是否足以使另一个应用程序扮演与之通信的中央角色。如果不是这样,我需要添加什么以制作一个最小的外围应用程序?