我正在尝试在两个设备(两个iPhone)之间发送数据(图像)。 此代码用于通告的CBPeripheralManager:
func peripheralManagerDidUpdateState(_ peripheral: CBPeripheralManager) {
switch peripheral.state {
case .unknown:
print("central.state is .unknown")
case .resetting:
print("central.state is .resetting")
case .unsupported:
print("central.state is .unsupported")
case .unauthorized:
print("central.state is .unauthorized")
case .poweredOff:
print("central.state is .poweredOff")
case .poweredOn:
print("central.state is .poweredOn")
updateAdvertisingData()
}
}
func updateAdvertisingData() {
if (cameraPeripheralManager.isAdvertising) {
cameraPeripheralManager.stopAdvertising()
}
let advertisementData = String(format: "%@", "advertisementData")
char = CBMutableCharacteristic(type: CHAR_UUID, properties: [.notify], value: nil, permissions: [.readable])
myRoei = CBMutableService(type: RX_UUID, primary: true)
myRoei.characteristics = [char]
cameraPeripheralManager.add(myRoei)
cameraPeripheralManager.startAdvertising([CBAdvertisementDataServiceUUIDsKey:[RX_UUID], CBAdvertisementDataLocalNameKey: advertisementData])
}
func peripheralManager(_ peripheral: CBPeripheralManager, central: CBCentral, didSubscribeTo characteristic: CBCharacteristic) {
print("didSubscribeTo")
if let img = UIImage(named: "maiden") {
let data = UIImagePNGRepresentation(img)
self.sendData(data: data!)
}
}
func sendData(data: Data){
data.withUnsafeBytes { (u8Ptr: UnsafePointer<UInt8>) in
let mutRawPointer = UnsafeMutableRawPointer(mutating: u8Ptr)
let uploadChunkSize = 20
let totalSize = data.count
var offset = 0
while offset < totalSize {
let chunkSize = offset + uploadChunkSize > totalSize ? totalSize - offset : uploadChunkSize
let chunk = Data(bytesNoCopy: mutRawPointer+offset, count: chunkSize, deallocator: Data.Deallocator.none)
offset += chunkSize
print("The offset is: + \(offset)")
print("Total size is: + \(totalSize)")
cameraPeripheralManager.updateValue(chunk, for: char, onSubscribedCentrals: nil)
}
}
}
在CBCentralManager中,我使用的是didUpdateValueFor
特征,它始终为零。
func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
print(characteristic.value as Any)
switch characteristic.uuid {
case CHAR_UUID:
print("Char value: \(String(describing: characteristic.value))")
case RX_UUID: break
//
default:
print("Unhandled Characteristic UUID: \(characteristic.uuid)")
}
}
我做错了什么?