Home > Articles > Mobile Application Development & Programming

  • Print
  • + Share This
Like this article? We recommend

Appendix: Listing for ViewController.swift

This listing shows all the bold code that required for the project, as described in the various sections in this article.

import UIKit
import CoreBluetooth

class ViewController: UIViewController,
    CBCentralManagerDelegate,
    CBPeripheralDelegate,

    UIImagePickerControllerDelegate,
    UINavigationControllerDelegate {

    @IBOutlet weak var btnLeft: UIButton!
    @IBOutlet weak var btnRight: UIButton!
    @IBOutlet weak var txtStatus: UILabel!

    var serviceKeyPressesUDID: CBUUID!
    var characteristicKeyPressesUDID: CBUUID!

    var connectedSensorTag: CBPeripheral!

    var centralManager: CBCentralManager!
    var picker:UIImagePickerController!

    @IBAction func btnScan(sender: AnyObject) {
        //---scan for peripheral devices---
        self.centralManager.scanForPeripheralsWithServices(nil, options:nil)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        serviceKeyPressesUDID = CBUUID(string:"FFE0")

        characteristicKeyPressesUDID =
CBUUID(string:"FFE1")
        self.centralManager = CBCentralManager(delegate: self, queue: nil)
    }

    func centralManagerDidUpdateState(central: CBCentralManager!) {
        println("centralManagerDidUpdateState:")

        switch (central.state) {
        case .PoweredOff:
            println("CBCentralManagerStatePoweredOff")
        case .Resetting:
            println("CBCentralManagerStateResetting")
        case .PoweredOn:
            println("CBCentralManagerStatePoweredOn")
            //---scan for peripheral devices---
            self.centralManager.scanForPeripheralsWithServices(nil, options:nil)


        case .Unauthorized:
            println("CBCentralManagerStateUnauthorized")
        case .Unsupported:
            println("CBCentralManagerStateUnsupported")
        default:
            println("CBCentralManagerStateUnknown")
        }
    }


    //---fired when peripheral devices are found---
    func centralManager(central: CBCentralManager!,
        didDiscoverPeripheral peripheral: CBPeripheral!,
        advertisementData: [NSObject : AnyObject]!,
        RSSI: NSNumber!) {

        //---print out the name of the scanned peripheral---

        println("Discovered \(peripheral.name)")
        //---print out the UUID of the scanned peripheral---
        //---you can save this value so that next time you can reconnect
        // back to it---

        println("NSUUID string
\(peripheral.identifier.UUIDString)")

        //---as long as you find one SensorTag, stop the scanning---
        var range = (peripheral.name as NSString).rangeOfString("Sensor")
        if (range.location != NSNotFound) {
            connectedSensorTag = peripheral

            self.centralManager.stopScan()
            //---save the peripheral---
            //---connect to the peripheral---
            self.centralManager.connectPeripheral(peripheral, options:nil)
            self.txtStatus.text = "Connected!"
        }
    }

    func centralManager(central: CBCentralManager!,
        didConnectPeripheral peripheral: CBPeripheral!) {
        println("Peripheral connected:
\(peripheral.name)")
        peripheral.delegate = self

        //---discover the specified service---
        var services = [serviceKeyPressesUDID]
        peripheral.discoverServices(services)
    }

    func centralManager(central: CBCentralManager!,
        didDisconnectPeripheral peripheral: CBPeripheral!,
        error: NSError!) {
        if connectedSensorTag == peripheral {
            self.txtStatus.text = "Disconnected!"
        }
    }

    func peripheral(peripheral: CBPeripheral!,
        didDiscoverServices error: NSError!) {
        for service in peripheral.services {
            println(
                "P: \(peripheral.name) - Discovered service S:'\(service.UUID)'")

            if service.UUID == serviceKeyPressesUDID {
                //---discover the specified characteristic of the service---
                var characteristics =
[characteristicKeyPressesUDID]

                //---discover the characteristics of the service---
                peripheral.discoverCharacteristics(characteristics,
                    forService: service as CBService)
            }
        }
    }

    func peripheral(peripheral: CBPeripheral!,
        didDiscoverCharacteristicsForService service: CBService!,
        error: NSError!) {

        for characteristic in service.characteristics {
            //---look for the characteristic that allows you to subscribe to---
            if characteristic.UUID == characteristicKeyPressesUDID {
                //---subscribe to the characteristic---
                peripheral.setNotifyValue(true,
                    forCharacteristic:characteristic as CBCharacteristic)
            }
        }
    }

    func peripheral(peripheral: CBPeripheral!,
        didUpdateNotificationStateForCharacteristic
        characteristic: CBCharacteristic!,
        error: NSError!) {
        if (error != nil) {
            println(
              "Error changing notification state:
\(error.localizedDescription)")
        } else {
            println("Characteristic's value subscribed")

            //---show camera preview---
            self.displayCamera()
        }
    }

    func peripheral(peripheral: CBPeripheral!,
        didUpdateValueForCharacteristic characteristic: CBCharacteristic!,
        error: NSError!) {
        if characteristic.UUID == characteristicKeyPressesUDID {
            var keyPressed:UInt16 = 0
            characteristic.value.getBytes(&keyPressed, length:
sizeof(UInt16))

            //---legends---
            // 1 - right button
            // 2 - left button
            // 0 - button released
            // 3 - both buttons pressed
            println("\(keyPressed)")
            switch (keyPressed) {
            case 0:
                //---a button is lifted---
                self.btnLeft.selected = false
                self.btnRight.selected = false
            case 1:
                //---right button pressed---
                self.btnRight.selected = true
                self.btnLeft.selected = false


                //---hide the camera---
                if picker != nil {
                    picker.dismissViewControllerAnimated(true, completion: nil)
                }
            case 2:
                //---left button pressed---
                self.btnLeft.selected = true
                self.btnRight.selected = false


                if picker != nil {
                    //---if the camera preview is already showing---
                    if picker.view.window != nil {
                        self.takePicture()
                    } else {
                        //---show the camera preview---
                        self.displayCamera()
                    }
                }
            case 3:
                //---both buttons pressed---
                self.btnLeft.selected = true
                self.btnRight.selected = true
            default:
                return
            }
            return
        }
    }


    func displayCamera() {
        picker = UIImagePickerController()
        picker.delegate = self
        picker.sourceType =
UIImagePickerControllerSourceType.Camera
        picker.cameraDevice =
UIImagePickerControllerCameraDevice.Front
        picker.showsCameraControls = false
        self.presentViewController(picker, animated:true, completion:nil)
    }


    func takePicture() {
        picker.takePicture()
    }


    //---save the snapshot taken to the Photos album---
    func imagePickerController(picker: UIImagePickerController,
        didFinishPickingMediaWithInfo info: [NSObject : AnyObject])
{
        var image = info[UIImagePickerControllerOriginalImage] as UIImage
        UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
    }


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


}
  • + Share This
  • 🔖 Save To Your Account