Home>

I want to exchange data using Swift's Core Bluetooth, but I don't understand the mechanism of data exchange between peripherals and central. I want to send a UIImage from a peripheral and Central receives it and displays it.
Could you tell me something small?

I wrote to change UIImage to data with the SendImage () function on the peripheral side and send it to central with updatevalue.
I don't know how the central side should receive this data.

extension UIImage {
    public func toPNGData ()->Data {
        guard let data = self.pngData () else {
            return Data ()
        }
        return data
    }
}
    private func sendImage () {
        guard let transferCharacteristic = transferCharacteristic else {
            return
        }
        let chunk = pngData
        os_log ("% d bytes from image", chunk.count)
        peripheralManager.updateValue (pngData, for: transferCharacteristic, onSubscribedCentrals: nil)
        os_log ("Sent data of image")
    }
//abridgement
    func peripheralManager (_ peripheral: CBPeripheralManager, central: CBCentral, didSubscribeTo characteristic: CBCharacteristic) {
        os_log ("Central subscribed to characteristic")
        imageToSend = UIImage (named: "turtlerock")!
        pngData = imageToSend.toPNGData ()
        sendDataIndex = 0
        connectedCentral = central
        sendImage ()
    }
Supplementary information

peripheral os_log
139102 bytes from image
Sent data of image
Is displayed, but it seems that it has not been successfully sent to Central.