create a bluetooth connection in swift

To create a bluetooth connection in Swift, you need to use the CoreBluetooth framework. Here are the steps to create a bluetooth connection:

  1. Import the CoreBluetooth framework in your project.
import CoreBluetooth
21 chars
2 lines
  1. Set up your central manager to scan for and connect to peripherals.
class ViewController: UIViewController, CBCentralManagerDelegate {
    var centralManager: CBCentralManager!
    var peripheral: CBPeripheral!

    override func viewDidLoad() {
        centralManager = CBCentralManager(delegate: self, queue: nil)

    func centralManagerDidUpdateState(_ central: CBCentralManager) {
        if central.state == .poweredOn {
            centralManager.scanForPeripherals(withServices: nil, options: nil)
        } else {
            print("Bluetooth not available.")

    func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
        self.peripheral = peripheral
        centralManager.connect(peripheral, options: nil)

    func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
        print("Connected to peripheral.")
        // Now you can start discovering services and characteristics on the peripheral.

    func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) {
        print("Failed to connect to peripheral.")
1217 chars
34 lines
  1. Implement the CBPeripheralDelegate methods to discover services and characteristics on the peripheral.
extension ViewController: CBPeripheralDelegate {

    func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
        peripheral.delegate = self

    func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) {
        guard let services = else { return }
        for service in services {
            print("Discovered service: \(service.uuid)")
            peripheral.discoverCharacteristics(nil, for: service)

    func peripheral(_ peripheral: CBPeripheral, didDiscoverCharacteristicsFor service: CBService, error: Error?) {
        guard let characteristics = service.characteristics else { return }
        for characteristic in characteristics {
            print("Discovered characteristic: \(characteristic.uuid)")
877 chars
23 lines
  1. Connect to your peripheral by implementing the CBCentralManagerDelegate methods.

This code will help you get started with creating a bluetooth connection in Swift. Don't forget to request permission to use Bluetooth in your app's Info.plist file.

gistlibby LogSnag