Hubert
Hubert

Reputation: 11

Swift iOS BLE writeValue sends data once

For some time I try to create communication between the iPhone <-> Bluetooth 4.0 LE <-> PC. Searching the internet I found a lot of solutions to support BLE in Swift. I created a small program that detects BLE device detects the characteristics and able to send some data to the BLE device. This BLE device is connected to the PC via USB (COM port). I use RX and TX to read and send data.

What's the problem... After detecting and connecting to BLE device, I try to send a String from the iPhone trough BLE device to display it on the PC. The first attempt to send data succeeds and this string from iPhone shows in COM monitor, but when I try again to send this String the data are not arriving. I noticed that equally after repeating 30 times a String that I want to send is coming. Then again I must repeat sending 30 times, and again String comes.

My code to send data

@IBAction func sendButtonAction(sender: AnyObject) 
{
    let textToSend: String = "Some text"
    let data = textToSend.dataUsingEncoding(NSUTF8StringEncoding)

    let txcharact: CBCharacteristic = TXCharacteristic!

    self.discoveredPeripheral?.writeValue(data!, forCharacteristic: txcharact, type: CBCharacteristicWriteType.WithResponse)    
}

Maybe someone had a similar problem ... Please help Sorry for my english.

Best regards Hubert

Upvotes: 1

Views: 1419

Answers (1)

Joshua Nozzi
Joshua Nozzi

Reputation: 61228

Your use of CBCharacteristicWriteWithResponse.WithResponse specifically asks for either an acknowledgement of success or an error describing the failure. At a guess, either it's waiting for you to handle one or more previous responses or (more likely) it's giving you an error you're ignoring. That it works again every 30 attempts suggests to me some buffer is full and possibly resetting the connection or transaction.

Don't just copy/paste code examples into your project without taking the time to read the documentation and understand exactly what that code does. I've never done anything with this API but that stuck out at me like a sore thumb within 10 seconds of glancing at the docs for your write call.

Upvotes: 4

Related Questions