美文网首页
swift 蓝牙开发简单demo

swift 蓝牙开发简单demo

作者: UILable攻城狮 | 来源:发表于2023-08-02 10:05 被阅读0次
import UIKit
import CoreBluetooth

class BluetoothKeyDemoViewController: UIViewController, CBCentralManagerDelegate {
    // 蓝牙相关属性
    private var centralManager: CBCentralManager!
    private var targetPeripheral: CBPeripheral?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 初始化中央管理器
        centralManager = CBCentralManager(delegate: self, queue: nil)
    }
    
    // MARK: - CBCentralManagerDelegate
    
    func centralManagerDidUpdateState(_ central: CBCentralManager) {
        if central.state == .poweredOn {
            // 蓝牙已启用,开始扫描设备
            centralManager.scanForPeripherals(withServices: nil, options: nil)
        }
    }
    
    func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
        // 找到目标设备后停止扫描并保存设备
        if peripheral.name == "Your Bluetooth Key Device Name" {
            centralManager.stopScan()
            targetPeripheral = peripheral
            
            // 连接设备
            centralManager.connect(targetPeripheral!, options: nil)
        }
    }
    
    func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
        // 连接成功,可用于发送指令
        // 在这里你可以实现发送开锁指令等相关功能
    }
}
参考例子
https://blog.csdn.net/weixin_33871366/article/details/93666184

相关文章

  • 蓝牙开发

    iOS蓝牙开发 Bluetooth蓝牙CoreBluetooth 蓝牙中心设备的实现 蓝牙外设的实现 有Demo ...

  • iOS蓝牙开发 Bluetooth蓝牙CoreBluetooth

    iOS蓝牙开发 Bluetooth蓝牙CoreBluetooth 蓝牙中心设备的实现 蓝牙外设的实现 有Demo ...

  • iOS - Swift 浅析

    Swift开发入门-基础知识,附demo - 简书 Swift开发入门-进阶知识(一),附demo - 简书 Sw...

  • ios蓝牙参考

    参考文章:iOS中的蓝牙开发iOS-BLE蓝牙开发demo 官网 转载 CenteralManager学习笔记

  • iOS蓝牙开发:蓝牙的连接和数据的读写

    蓝牙开发说简单也简单,说不简单也有点难,开发人员在首次开发蓝牙前首先需要搞清楚蓝牙开发的概念,还要了解掌握蓝牙开发...

  • Swift蓝牙开发

    github demo链接 新项目中要用蓝牙开发,把漆面仪测量到的数据通过蓝牙传给app,一般需要设备提供方提供开...

  • Xcode Source Editor Extension

    开发环境:Xcode 9 开发语言:Swift 4 Demo gif:Kapture 2017-11-07 at ...

  • iOS之仿支付宝刮奖

    现在在学swift,之前说要和大家分享的小demo就是这个了,demo本身很简单,由于初学swift,可能有些代码...

  • Electron开发 —— 简单demo之整合vue

    总得有个开始 前置条件: Electron开发 —— 简单demo vue开发 —— 简单demo vue 2.x...

  • iOS 蓝牙4.0简单Demo

    使用CBCentralMannager模式Demo样式: 1.导入CoreBluetooth框架 2.遵守CBCe...

网友评论

      本文标题:swift 蓝牙开发简单demo

      本文链接:https://www.haomeiwen.com/subject/lsjhpdtx.html