iOS Bluetooth peripheralManagerDidUpdateState never called

爱⌒轻易说出口 提交于 2019-12-06 21:23:34

The object myPeripheralManager is deallocated as soon as viewDidLoad method returns, as you have only one reference pointing to this object and it goes out of scope.

The solution is to create a property in ViewController which references the instance of CBPeripheralManager:

@interface ViewController()
@property (nonatomic, strong) CBPeripheralManager *myPeripheralManager;
@end

and then initialise the property in viewDidLoad:

self.myPeripheralManager = myPeripheralManager = [[CBPeripheralManager alloc] initWithDelegate:(id<CBPeripheralManagerDelegate>)self queue:nil options:nil];

You may want to read more about memory management (in particular, Automatic Reference Counting) in Objective-C.

My solution on this matter is:

import UIKit
import CoreBluetooth

class BluetoothManager: NSObject, CBPeripheralManagerDelegate {

    static let sharedInstance = BluetoothManager()

    var bluetoothPeripheralManager: CBPeripheralManager?


    override fileprivate init() {
    }

    func start() {
        bluetoothPeripheralManager = CBPeripheralManager(delegate: self, queue: nil, options: nil)

    }

    // MARK - CBCentralManagerDelegate
    func peripheralManagerDidUpdateState(_ peripheral: CBPeripheralManager) {

        var statusMessage = ""

        switch peripheral.state {
        case .poweredOn:
            statusMessage = "Bluetooth Status: Turned On"

        case .poweredOff:
            statusMessage = "Bluetooth Status: Turned Off"

        case .resetting:
            statusMessage = "Bluetooth Status: Resetting"

        case .unauthorized:
            statusMessage = "Bluetooth Status: Not Authorized"

        case .unsupported:
            statusMessage = "Bluetooth Status: Not Supported"

        default:
            statusMessage = "Bluetooth Status: Unknown"
        }

        print(statusMessage)

        if peripheral.state == .poweredOff {
            //TODO: Update this property in an App Manager class
        }
    }}

Usage:

BluetoothManager.sharedInstance.start()

Start up your up and turn/off and bluetooth a log message should appear indicating bluetooth status.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!