任意苹果设备都可以作为蓝牙外设进行设置。
苹果蓝牙后台的限制,原本广播会有两个段分别是localName和serviceUUID这两块,但现在后台广播时,是不发送在这两段的。
let peripheralManager = CBPeripheralManager.init(delegate: self, queue: DispatchQueue.main)
public func setupServiceAndCharacteristics() {
// 创建服务
let serviceID = CBUUID(string: kServiceUUID)
let service = CBMutableService(type: serviceID, primary: true)
// 创建服务中的特征
let characteristicID = CBUUID(string: kChARACTERISTICUUID)
let characteristic = CBMutableCharacteristic(type: characteristicID, properties: [.read, .write, .notify], value: nil, permissions: [.readable, .writeable])
// 特征添加进服务
service.characteristics = [characteristic]
// 服务加入管理
self.peripheralManager?.add(service)
}
let tempState = self.peripheralManager?.state ?? .unknown
let sendSuccess: Bool = self.peripheralManager.updateValue(self.textField.text.data(using: NSUTF8StringEncoding), forCharacteristic: self.characteristic, onSubscribedCentrals: nil)
CBPeripheralManagerDelegate
func peripheralManagerDidUpdateState(_ peripheral: CBPeripheralManager) {
print(peripheral.state)
delegate?.peripheralUpdateState(peripheral)
}
func peripheralManager(_ peripheral: CBPeripheralManager, didReceiveRead request: CBATTRequest) {
// 请求中的数据,这里把文本框中的数据发给中心设备
// request.value = self.textField.text.data(using: NSUTF8StringEncoding)
// 成功响应请求
// peripheral.respondToRequest(request, withResult: CBATTErrorSuccess)
}
func peripheralManager(_ peripheral: CBPeripheralManager, didReceiveWrite requests: [CBATTRequest]) {
// 写入数据的请求
let request = requests.last
let data = request?.value
delegate?.peripheralDidReceiveWrite(data)
}
func peripheralManager(_ peripheral: CBPeripheralManager, central: CBCentral, didSubscribeTo characteristic: CBCharacteristic) {
print(#function)
}
// 取消订阅回调
func peripheralManager(_ peripheral: CBPeripheralManager, central: CBCentral, didUnsubscribeFrom characteristic: CBCharacteristic) {
print(#function)
}
}
self.peripheralManager?.startAdvertising(periData)
注意⚠️:测试时beacon广播CLBeacon未检测到iPhone设备。 即使使用 Turning an iOS device into an iBeacon device 也没有结果(如果帮助不胜感激)
/// 开始发送广播
public func startBroadcasting(major: UInt16 = 0, minor: UInt16 = 0, peripheralData: [String: Any]? = nil) {
// 为beacon基站创建一个唯一标示
guard let myUUID = UUID(uuidString: kBeaconUUIDString) else {
return
}
let constraint = CLBeaconIdentityConstraint(uuid: myUUID, major: major, minor: minor)
let myBeaconRegion = CLBeaconRegion.init(beaconIdentityConstraint: constraint, identifier: kBeaconidentifier)
// 获取该Beacon区域的信号信息
var periData = myBeaconRegion.peripheralData(withMeasuredPower: nil) as? [String: Any]
peripheralData?.forEach { (key: String, value: Any) in
periData?[key] = value
}
// 创建并广播Beacon信号
self.peripheralManager?.startAdvertising(periData)
}
self.peripheralManager?.stopAdvertising()