加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

swift – 为什么协议功能没有被调用

发布时间:2020-12-14 04:28:19 所属栏目:百科 来源:网络整理
导读:我有一个实现协议的文件和另一个调用该协议的文件 //// DeviceBLE.swift//import Foundationimport CoreBlueToothimport QuartzCoreimport UIKitclass DeviceBLE: NSObject,CBCentralManagerDelegate,CBPeripheralDelegate { var centralManager : CBCentral
我有一个实现协议的文件和另一个调用该协议的文件

//
//  DeviceBLE.swift
//

import Foundation
import CoreBlueTooth
import QuartzCore
import UIKit

class DeviceBLE: NSObject,CBCentralManagerDelegate,CBPeripheralDelegate {

    var centralManager : CBCentralManager!

    init() {
        super.init()
        centralManager = CBCentralManager(delegate: self,queue: nil)
    }

    func centralManagerDidUpdateState(central: CBCentralManager!){
        // Determine the state of the peripheral
        if (central.state == .PoweredOff) {
            println("CoreBluetooth BLE hardware is powered off")
        }
        else if (central.state == .PoweredOn) {
            println("CoreBluetooth BLE hardware is powered on and ready")
            //            connectPeripheral(_ peripheral: CBPeripheral!,//                options options: [NSObject : AnyObject]!)
        }
        else if (central.state == .Unauthorized) {
            println("CoreBluetooth BLE state is unauthorized")
        }
        else if (central.state == .Unknown) {
            println("CoreBluetooth BLE state is unknown")
        }
        else if (central.state == .Unsupported) {
            println("CoreBluetooth BLE hardware is unsupported on this platform")
        }
    }
}

这是文件调用

//  ViewController.swift
//  BleTest
import Foundation
import CoreBlueTooth
import QuartzCore
import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view,typically from a nib.
        var myBle = DeviceBLE()
     }

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

问题是当实例化DeviceBle时,不会调用centralManagerDidUpdateState.我不明白我做错了什么.有人可以帮忙吗?

解决方法

可能是您正在将myBle设置为局部变量,因此在viewDidLoad方法的执行结束时,将取消分配DeviceBLE.尝试使myBle成为ViewController类的实例变量.

class ViewController: UIViewController {
    var myBle: CBCentralManager?

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view,typically from a nib.
        self.myBle = DeviceBLE()
      }

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

另外,在您的委托方法中.最好使用switch语句而不是几个if语句.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读