Bluetooth Chat Room App

You should first read Bluetooth & Bluetooth fundamentalsdiscovering peripheralsconnecting peripherals for building strong fundamentals on ble.

I like to thanks Efe Cem Kocabas for providing a very good sample project on bluetooth low energy. git link.

I will discuss about ChatViewController.swift.

The Goal of this app is to make our iOS device act as both peripheral and central. Note that Central does not connect to central & Peripheral does not connect to peripheral.

Let’s say chat will happen between Device A and Device B.

Init peripheral and central:

As soon as above code will execute didUpdateState delegate methods of peripheral manager and central manager will be called automatically.

CentralManager Delegate:

PeripheralManager Delegate:

From theory a service contains characteristics. So , init serivce use CBMutableService and CBMutableCharacteristic. Set CBMutableCharacteristic object array to CBMutableService.

Advertisement set up: Peripheral must advertise using startAdvertising.

Up to the above set up this is what it looks like:

centralManager?.scanForPeripherals will trigger the didDiscoverDelegate method of central manager. Hold reference to discovered peripheral.

After discovering a peripheral, the logical design looks like this:

Note : When we say discovered, it means discovered there is still no connection between peripheral and central.

If you run app and go to chat screen, you will find a textfield and a send button.

Selector of send button is defined like this:

This will trigger central manager didConnet delegate method.

At this time our diagram will look like this:

Now A and B are connected.

Finally the below two will be called:

and peripheral.writeValue will trigger didReceiveWrite:

Happy Coding 🙂