iOS setup as a Bluetooth peripheral

1. Description

Any Apple device can be set up as a Bluetooth peripheral.
Due to limitations of Apple's Bluetooth background, originally there were two segments in the broadcast, namely localName and serviceUUID, but now when broadcasting in the background, these two segments are not sent.

2. Set up Bluetooth peripherals

1. Initialize peripheral center

let peripheralManager = CBPeripheralManager.init(delegate: self, queue: DispatchQueue.main)

2. Create peripheral services

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)
    }

3. Get the Bluetooth status of peripherals

let tempState = self.peripheralManager?.state ?? .unknown

4. Send Bluetooth data

let sendSuccess: Bool = self.peripheralManager.updateValue(self.textField.text.data(using: NSUTF8StringEncoding), forCharacteristic: self.characteristic, onSubscribedCentrals: nil)

3. Peripheral agent

CBPeripheralManagerDelegate

1. Status change callback

    func peripheralManagerDidUpdateState(_ peripheral: CBPeripheralManager) {
        print(peripheral.state)
        delegate?.peripheralUpdateState(peripheral)
    }

2. Callback when the central device reads data

    func peripheralManager(_ peripheral: CBPeripheralManager, didReceiveRead request: CBATTRequest) {
        // 请求中的数据,这里把文本框中的数据发给中心设备
//        request.value = self.textField.text.data(using: NSUTF8StringEncoding)
        // 成功响应请求
//        peripheral.respondToRequest(request, withResult: CBATTErrorSuccess)
    }

3. Callback when the central device writes data

    func peripheralManager(_ peripheral: CBPeripheralManager, didReceiveWrite requests: [CBATTRequest]) {
        // 写入数据的请求
        let request = requests.last
        
        let data = request?.value
        delegate?.peripheralDidReceiveWrite(data)
    }

4. Subscription Alerts

    func peripheralManager(_ peripheral: CBPeripheralManager, central: CBCentral, didSubscribeTo characteristic: CBCharacteristic) {
        print(#function)
    }
    
    // 取消订阅回调
    func peripheralManager(_ peripheral: CBPeripheralManager, central: CBCentral, didUnsubscribeFrom characteristic: CBCharacteristic) {
        print(#function)
    }
}

4. Send broadcast data

1. Send different broadcasts

self.peripheralManager?.startAdvertising(periData)

2. beacon broadcast

Note⚠️: When testing, the beacon broadcast CLBeacon did not detect the iPhone device. Even using Turning an iOS device into an iBeacon device has no results (help would be greatly appreciated)

/// 开始发送广播
    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)
    }

3. Stop broadcasting

self.peripheralManager?.stopAdvertising()

Guess you like

Origin blog.csdn.net/guoxulieying/article/details/133038983