Josh Paya
Josh Paya

Reputation: 33

Updating code to Swift 3

I am a beginner to programming with swift and programming in general. I am currently working on an app which allows one phone to send a message (peripheral) to another which will receive the message (central). I have taken most of the code from an app built using swift 2 and have tweaked it slightly to remove any errors. As a result, my code is a jumble of swift 2/3 (or so I have been told). I am not sure how to update this code fully to swift 3 which I need someones help to do. I believe it is the IBActions and delegates that are outdated but I am completely clueless on how to amend it.

I have tried running the app and it runs successfully but when I press any of the buttons nothing happens as far as I can tell. I have a basic understanding of what my code does and what each function is there for but I find myself stuck on what to do for it to work. If anyone has experience working with Bluetooth via swift and can see what I am doing wrong or perhaps if I haven't included something important. I am led to believe the issue is that all the code has not been updated to swift 3 but I can't be sure. I have read the Apple documentation for Core bluetooth.

PS: I know this question is very vague as I am unsure on what part of my code I need to fix so it is very difficult to make it specific to a single issue. Sorry!

import UIKit
import CoreBluetooth

class ViewController: UIViewController, CBPeripheralManagerDelegate, CBCentralManagerDelegate, CBPeripheralDelegate {
    let messageUUID = CBUUID(string: "053D6600-821E-46A7-AC25-43A81D948E8B")
    let inputUUID = CBUUID(string: "49A79D26-5323-4374-81EA-29B099AF85C8")
    let otherUUID = CBUUID(string: "053D6600-821E-46A7-AC25-43A81D948E87")
    var peripheralManager: CBPeripheralManager!
    var characteritic: CBMutableCharacteristic!
    var getDataPeripheralCharacteristic: CBMutableCharacteristic!
    var service: CBMutableService!
    var outputData:String = ""
    var centralManager: CBCentralManager!
    var connectingPeripheral: CBPeripheral?
    var centralWriteCharacteristic: CBCharacteristic!


    @IBOutlet var inputLabel: UITextField!
    @IBOutlet weak var outputLabel: UILabel!
    override func viewDidLoad() {
        super.viewDidLoad()
    }


    @IBAction func centralMode(_ sender: UIButton) {
        centralManager = CBCentralManager(delegate: self, queue: nil)
        peripheralManager = nil
    }


    @IBAction func peripheralMode(_ sender: UIButton) {
        peripheralManager = CBPeripheralManager(delegate: self, queue: nil)
        centralManager = nil
    }




    @IBAction func sendData(_ sender: UIButton) {
        if (peripheralManager != nil) {
            let passed = peripheralManager.updateValue(inputLabel.text!.data(using: String.Encoding.utf8)!, for: characteritic!, onSubscribedCentrals: nil)
            if passed == false {
                print("error couldn't send data")
            }
        }
        if (centralManager != nil) {
            if (connectingPeripheral != nil) {
                connectingPeripheral?.writeValue(inputLabel.text!.data(using: String.Encoding.utf8)!, for: centralWriteCharacteristic, type: CBCharacteristicWriteType.withResponse)
            }
        }
    }

    func peripheralManagerDidUpdateState(_ peripheral: CBPeripheralManager) {
        if (peripheral.state == .poweredOn) {
            characteritic = CBMutableCharacteristic(type: messageUUID, properties: CBCharacteristicProperties.notify, value: nil, permissions: CBAttributePermissions.readable)
            getDataPeripheralCharacteristic = CBMutableCharacteristic(type: inputUUID, properties:
                CBCharacteristicProperties.write, value: nil, permissions: CBAttributePermissions.writeable)
            service = CBMutableService(type: otherUUID, primary: true)
            service.characteristics = [characteritic!, getDataPeripheralCharacteristic!]
            peripheralManager!.add(service)
        }
    }


    func peripheralManager(peripheral: CBPeripheralManager, didAddService service: CBService, error: NSError?) {
            peripheral.stopAdvertising()
        let identifier = Bundle.main.bundleIdentifier!
        let manufacturerData = identifier.data(using: String.Encoding.utf8, allowLossyConversion: false)
        let dataToBeAdvertised:[String: Any] = [
            CBAdvertisementDataLocalNameKey : "Sample peripheral",
            CBAdvertisementDataManufacturerDataKey : manufacturerData as Any,
            CBAdvertisementDataServiceUUIDsKey : [messageUUID, inputUUID],
            ]

        peripheralManager.startAdvertising(dataToBeAdvertised)
    }




    func peripheralManager(peripheral: CBPeripheralManager, didReceiveWriteRequests requests: [CBATTRequest]) {
        for request in requests {
            if (request.characteristic.uuid.uuidString == inputUUID.uuidString) {
                outputData = String(data: request.value!, encoding: String.Encoding.utf8)!
                outputLabel.text = outputData
            }
        }
    }

    func peripheralManager(peripheral: CBPeripheralManager, didReceiveReadRequest request: CBATTRequest) {
    }

    func peripheralManager(peripheral: CBPeripheralManager, central: CBCentral, didSubscribeToCharacteristic characteristic: CBCharacteristic) {
        outputLabel.text = "Press send message"
        print("Now connected")
    }


        func centralManagerDidUpdateState(_ central: CBCentralManager) {
            if central.state == .poweredOn {
                centralManager.scanForPeripherals(withServices: nil, options: nil)
                //search for peripheral device
            }
        }


        //when peripheral is discovered, this method is called

        private func centralManager(central: CBCentralManager, didDiscoverPeripheral peripheral: CBPeripheral, advertisementData: [String : AnyObject], RSSI: NSNumber) {
            self.centralManager.stopScan();
            self.connectingPeripheral = peripheral;
            peripheral.delegate = self;
            centralManager.connect(peripheral, options: nil)
        }

        //if connection request from central is succesfull, this method is called
        func centralManager(central: CBCentralManager, didConnectPeripheral peripheral: CBPeripheral) {
            peripheral.delegate = self;
            peripheral.discoverServices(nil)
        }

        //if central discovers services, this method is called
        private func peripheral(peripheral: CBPeripheral, didDiscoverServices error: NSError?) {
            for service: CBService in peripheral.services! {
                peripheral.discoverCharacteristics(nil, for: service)
            }
        }

        private func peripheral(peripheral: CBPeripheral, didDiscoverCharacteristicsForService service: CBService, error: NSError?) {
            if (service.uuid.uuidString == otherUUID.uuidString) {
                guard let characteristics = service.characteristics else {
                    return
                }
                for characteristic in characteristics {
                    if characteristic.uuid.uuidString == messageUUID.uuidString {
                        peripheral.setNotifyValue(true, for: characteristic)
                } else if characteristic.uuid.uuidString == inputUUID.uuidString {
                    centralWriteCharacteristic = characteristic
                    }
                }
            }
        }


    private func peripheral(peripheral: CBPeripheral, didUpdateValueForCharacteristic characteristic: CBCharacteristic, error: NSError?) {
        if error != nil {
            print("Error reading characteristics");
        }
        if (characteristic.uuid == messageUUID) {
            outputData = String(data: characteristic.value!, encoding: String.Encoding.utf8)!
            print(outputData)
            outputLabel.text = outputData
        }
    }


}

Upvotes: 0

Views: 209

Answers (1)

rajat chauhan
rajat chauhan

Reputation: 178

If the issue is because of swift 2/3 mismatch. Try upgrading your code to swift3.

  1. Go to Xcode-edit-convert- to current swift syntax.
  2. This will lead to few build errors, identify them and fix them.
  3. Make your sure if you have any pod or cart file , do not forget to upgrade them as well.

Hopefully this should resolve your issue.

Upvotes: 1

Related Questions