CBService changed: How handle this in iOS 14 and 15?

Building my app with Xcode 13, a dependency threw an error related to the changes in CoreBluetooth: Some properties are now returned as optionals in iOS 15.

Wanting to fix that, I would like to make sure that the library will run on both iOS 15 and SDKs prior to that, but the current availability markers will not help me:

    func peripheralManager(_ peripheral: CBPeripheralManager, didAdd service: CBService, error: Error?) {
        let peripheral: CBPeripheral

        // So what I would like is something like this
        // But this does not work :(

        if  #available(iOS 15, *) {
            guard let nonOptional = service.peripheral else {
                return
            }
            peripheral = nonOptional
        } else {
            peripheral = service.peripheral
        }

        let result: CBPeripheral = peripheral
        print ("\(result)")
    }```

This code will cause the compiler to throw an error both on Xcode 13 and Xcode 12. 

Is there any good way to solve this?

Accepted Reply

Can you try something like this?

    func peripheralManager(_ peripheral: CBPeripheralManager, didAdd service: CBService, error: Error?) {
        let optPeripheral: CBPeripheral? = service.peripheral
        guard let peripheral = optPeripheral else {
            return
        }

        let result: CBPeripheral = peripheral
        print ("\(result)")
    }
  • Thank you! That worked!

Add a Comment

Replies

Can you try something like this?

    func peripheralManager(_ peripheral: CBPeripheralManager, didAdd service: CBService, error: Error?) {
        let optPeripheral: CBPeripheral? = service.peripheral
        guard let peripheral = optPeripheral else {
            return
        }

        let result: CBPeripheral = peripheral
        print ("\(result)")
    }
  • Thank you! That worked!

Add a Comment