API MISUSE: <CBPeripheralManager: 0x282c00070> can only accept this command while in the powered on

API MISUSE: <CBPeripheralManager: 0x282c00070> can only accept this command while in the powered on state

XPC connection invalid

//这里如果不用self.manager而是用let manager的话,会不弹出蓝牙授权框
//得在这个方法调用,peripheral: CBPeripheralManager状态为poweredOn的时候再添加service。 得用这个CBPeripheralManager添加service.如果你新创建一个CBPeripheralManager,用这个新的CBPeripheralManager添加service,由于系统不知道这个新的CBPeripheralManager状态还是会报上面的错误

正确的代码如下:

//
//  ViewController.swift
//  XYCBPeripheralManager
//
//  Created by macvivi on 2020/12/8.
//

import UIKit
import CoreBluetooth

class ViewController: UIViewController, CBPeripheralManagerDelegate{
    
    
    @IBAction func click(_ sender: Any) {
        addPeripheral()
    }
    
    
    func peripheralManagerDidUpdateState(_ peripheral: CBPeripheralManager) {
        print(#function)
        print(peripheral.state.rawValue)
        //得在这个方法调用,peripheral: CBPeripheralManager状态为poweredOn的时候再添加service。 得用这个CBPeripheralManager添加service.如果你新创建一个CBPeripheralManager,用这个新的CBPeripheralManager添加service,由于系统不知道这个新的CBPeripheralManager状态还是会报上面的错误
    }
    
    func peripheralManager(_ peripheral: CBPeripheralManager, didAdd service: CBService, error: Error?) {
        print(#function)
        print(error)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        print(CBPeripheralManager.authorization.rawValue)
        //这里如果不用self.manager而是用let manager的话,会不弹出蓝牙授权框
        self.manager = CBPeripheralManager.init(delegate: self, queue: nil, options: nil)
    }

    var manager: CBPeripheralManager?

    func addPeripheral() {
        print(CBPeripheralManager.authorization.rawValue)
         
        let customServiceUUID = CBUUID(string: "71DA3FD1-7E10-41C1-B16F-4430B506CDE7")
        let myCharacteristic = CBMutableCharacteristic(type: customServiceUUID, properties: .read, value: Data(), permissions: .readable)
        
        let myService = CBMutableService(type: customServiceUUID, primary: true)
        myService.characteristics = [myCharacteristic]

        self.manager!.add(myService)
    }
}

在这里插入图片描述
在这里插入图片描述

参考博客:
[CoreBluetooth] API MISUSE: can only accept this command while in the powered on state(iOS蓝牙)

蓝牙开发遇到的问题

相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页