Skip to content

Instantly share code, notes, and snippets.

@marktyers
Created December 17, 2015 18:49
Show Gist options
  • Select an option

  • Save marktyers/fa96e0a6f81eee4cf822 to your computer and use it in GitHub Desktop.

Select an option

Save marktyers/fa96e0a6f81eee4cf822 to your computer and use it in GitHub Desktop.

Revisions

  1. marktyers created this gist Dec 17, 2015.
    65 changes: 65 additions & 0 deletions ViewController.swift
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,65 @@

    import UIKit
    import CoreBluetooth

    class ViewController: UIViewController, CBCentralManagerDelegate, CBPeripheralManagerDelegate {

    var centralManager:CBCentralManager!
    var peripheralManager:CBPeripheralManager = CBPeripheralManager()
    let uuid:CBUUID = CBUUID(string: "DCEF54A2-31EB-467F-AF8E-350FB641C97B")

    override func viewDidLoad() {
    super.viewDidLoad()
    self.peripheralManager = CBPeripheralManager(delegate: self, queue: nil)
    self.centralManager = CBCentralManager(delegate: self, queue: nil)
    let advertisingData = [CBAdvertisementDataLocalNameKey:"my-peripheral", CBAdvertisementDataServiceUUIDsKey: uuid]
    peripheralManager.startAdvertising(advertisingData)
    centralManager.scanForPeripheralsWithServices([uuid], options: [ CBCentralManagerScanOptionAllowDuplicatesKey : true])
    }

    override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
    }

    func peripheralManagerDidStartAdvertising(peripheral: CBPeripheralManager, error: NSError?) {
    print("started advertising")
    print(peripheral)
    }

    func centralManager(central: CBCentralManager, didDiscoverPeripheral peripheral: CBPeripheral, advertisementData: [String : AnyObject], RSSI: NSNumber) {
    print("peripheral discovered")
    print("peripheral: \(peripheral)")
    print("advertisement: \(advertisementData)")
    if let data = advertisementData["kCBAdvDataServiceData"] {
    print("found advert data: \(data)")
    }
    print("RSSI: \(RSSI)")
    }

    func centralManager(central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: NSError?) {
    print("peripheral disconnected")
    print("peripheral: \(peripheral)")
    }

    func centralManagerDidUpdateState(central: CBCentralManager) {
    print("central state updated")
    print(central.description)
    if central.state == .PoweredOff {
    print("bluetooth is off")
    }
    if central.state == .PoweredOn {
    print("bluetooth is on")
    centralManager.scanForPeripheralsWithServices(nil, options: [ CBCentralManagerScanOptionAllowDuplicatesKey : true])
    }
    if central.state == .Unsupported {
    print("bluetooth is unsupported on this device")
    }
    }

    func peripheralManagerDidUpdateState(peripheral: CBPeripheralManager) {
    print("peripheral state updated")
    print("\(peripheral.description)")
    }

    }