Setting up communication 

To start communicating with the Bluetooth device, you'll need to setup a protocol that provides updates for local peripheral state and interactions with remote central devices.

That protocol would be CBPeripheralManagerDelegate, so add an extension to the ViewController and add CBPeripheralManagerDelegate.

extension ViewController: CBPeripheralManagerDelegate {

  func peripheralManagerDidUpdateState(_ peripheral: CBPeripheralManager) {
    switch peripheral.state {
    case .poweredOn:
        print("Peripheral Is Powered On.")
    case .unsupported:
        print("Peripheral Is Unsupported.")
    case .unauthorized:
    print("Peripheral Is Unauthorized.")
    case .unknown:
        print("Peripheral Unknown")
    case .resetting:
        print("Peripheral Resetting")
    case .poweredOff:
      print("Peripheral Is Powered Off.")
    @unknown default:
      print("Error")
    }
  }
}

The protocol’s requires one method, peripheralManagerDidUpdateState(_:), which Core Bluetooth calls whenever the peripheral manager’s state updates to indicate whether the peripheral manager is available.

Reading the Value of a Characteristic

Since peripheral.setNotifyValue has been called previously in the didDiscoverCharacteristicsFor method, you are able to set notifications or indications for incoming values registered to the rxcharacteristic.

Once receiving incoming values from a Bluetooth device, Core Bluetooth invokes didUpdateValueFor to handle that incoming data.

func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {

      var characteristicASCIIValue = NSString()

      guard characteristic == rxCharacteristic,

      let characteristicValue = characteristic.value,
      let ASCIIstring = NSString(data: characteristicValue, encoding: String.Encoding.utf8.rawValue) else { return }

      characteristicASCIIValue = ASCIIstring

      print("Value Recieved: \((characteristicASCIIValue as String))")
}

In didUpdateValueFor(), first create an instance of NSString, that will be  the characteristicASCIIValue variable to hold an incoming value, then convert it to an ASCII string, then print the converted ASCII value to the console.

Writing to a Characteristic

Before writing data to an external peripheral, you need to know how we want to write that data.

There are two types of CBCharacteristic write types. The CBCharacteristic write type can be either .withResponse or .withoutResponse.

The .withResponse property type gets a response from the peripheral to indicate whether the write was successful. The .withoutResponse doesn't send any response back from the peripheral.

To write to a characteristic you’ll need to write a value with an instance of NSData and do that by calling  writeValue(for: , type: CBCharacteristicWriteType.withResponse) method:

bluefruitPeripheral.writeValue(data!, for: txCharacteristic, type: CBCharacteristicWriteType.withResponse)

Create a new function that will communicate with the Bluetooth device. I've called this function writeOutgoingValue(), but call it whatever you'd like.

First, format the outgoing string as NSData. Then, make sure bluefruitPeripheral and txCharacteristic variables are not set to nil.  

Then add the writeValue method into your function.

func writeOutgoingValue(data: String){
      
    let valueString = (data as NSString).data(using: String.Encoding.utf8.rawValue)
    
    if let bluefruitPeripheral = bluefruitPeripheral {
          
      if let txCharacteristic = txCharacteristic {
              
        bluefruitPeripheral.writeValue(valueString!, for: txCharacteristic, type: CBCharacteristicWriteType.withResponse)
          }
      }
  }

Awesome. Now that you've given the app the ability to communicate with a Bluetooth device, hook up the device to the Arduino IDE.

Ok, now to hook up some quick UI to test out the app.

In your file hierarchy located on the left, locate and go to Main.storyboard. Here, create a button that will trigger the function to transmit the data to the Bluetooth device.

Above your navigation pane, select the "+" button to display a library of UI elements.

Now that you've opened up the UI library, press and slide "Button" onto you View Controller.

Ok, I gave my changed my button label to "Send Hello World", you can change it to your liking. 

Now connect the UI to the code. Press this icon on the upper right corner of your Navigation Pane, and locate your ViewController.swift file. 

Once you've done that, Control drag and drop the button to the ViewController.swift file. Instead if adding an Outlet, create an action and name it "buttonPress". 

Now head back into the ourViewController.swift file. Within the buttonPress method, add the writeOutgoingValue() method and add a string into the parameter. I've chosen to send "Hello Word". 

@IBAction func buttonPress(_ sender: Any) {
    writeOutgoingValue(data: "Hello World")
  }

Great! Now to set up communications on the Bluetooth device.

This guide was first published on Jul 27, 2017. It was last updated on Mar 08, 2024.

This page (Communication ) was last updated on Mar 08, 2024.

Text editor powered by tinymce.