0

I need some sample code to see how to transfer an audio file (or any other binary data) using CoreBlueTooth L2CAP channel. Assuming the file is not so small, let us say it is a few hundred kilobytes.

I am working on a small iOS app doing that, but it is only working half way.

At this point I can transfer a few thousand bytes, but it does not go further.

Just in case, this is the related code I have on the sending side:

let path = Bundle.main.path(forResource: "\(name)", ofType: nil)!,
url = URL(fileURLWithPath: path)

do {let audioData = try Data(contentsOf: url)
    // do something useful with audioData to send it
    // to the other device.
    ..........
    let bytesWritten = data.withUnsafeBytes {outStream!.write($0, maxLength: audioData.count)}

    if bytesWritten > 0 {
        ..........
    }

} catch {
    print("Error: \(error.localizedDescription)")
}

On the receiving side:

let inData = Data(reading: inStream)

if inData.count != 0 {
    // Data has been received.
    .......
}

I am obviously not showing much detail, but my code is missing some critical parts anyway, this is why I would be glad to find some little working sample in order to see how it works.

Michel
  • 10,303
  • 17
  • 82
  • 179
  • See https://github.com/paulw11/L2CapDemo/blob/master/L2CapDemo/CentralViewController.swift. In particular you need to make sure you're scheduling the streams on a runloop. See also https://stackoverflow.com/questions/57635965/using-corebluetooth-cbl2capchannel-to-move-data – Rob Napier Sep 01 '19 at 16:00
  • After checking my code (with the link you mention), it doesn't seem there is any problem with scheduling. But I am not sure what happens when in "let bytesWritten = data.withUnsafeBytes {ostream.write($0, maxLength: data.count)}", not all the bytes can be written. How the left bytes are handled is not clear to me. That may not happen in the demo, since it is only sending small pieces of text. But I want to handle audio files where I will not be able to send all the bytes at the same time. And I am in a kind of situation where I don't quite know what to do. – Michel Sep 02 '19 at 02:58
  • I am in fact already sending the first chunk with few thousand bytes of audio data, but stopped at this first chunk. – Michel Sep 02 '19 at 02:58
  • 1
    L2CAP has limited output capacity. you'll need to cycle back around when `hasSpaceAvailable` is true and send some more. L2CAP is not a fast protocol. – Rob Napier Sep 02 '19 at 13:37

0 Answers0