BLE在后台不起作用-iOS/Swift
创始人
2024-12-22 18:00:11
0

在应用程序的Info.plist文件中添加一些键值对,允许BLE在应用程序被推送到后台时继续操作。

  1. 添加以下键值对:

Privacy - Bluetooth Always Usage Description Privacy - Bluetooth Peripheral Usage Description

键值对的值应该是一个字符串,用于描述应用程序需要使用蓝牙的原因。

  1. 在AppDelegate.swift文件中,添加以下代码:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { // Override point for customization after application launch. UIApplication.shared.registerForRemoteNotifications() return true }

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { let deviceTokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)}) print("APNs device token: (deviceTokenString)") }

func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) { print(error.localizedDescription) }

  1. 在ViewController.swift文件中,添加以下代码:

import CoreBluetooth

class ViewController: UIViewController, CBCentralManagerDelegate {

var centralManager: CBCentralManager!

override func viewDidLoad() {
    super.viewDidLoad()

    centralManager = CBCentralManager(delegate: self, queue: nil, options: [CBCentralManagerOptionRestoreIdentifierKey: "MyCentralManager"])
}

func centralManagerDidUpdateState(_ central: CBCentralManager) {
    switch central.state {
    case .poweredOn:
        print("Bluetooth On")
        break
    case .poweredOff:
        print("Bluetooth Off")
        break
    case .unsupported:
        print("Bluetooth Unsupported")
        break
    case .unauthorized:
        print("Bluetooth Unauthorized")
        break
    case .resetting:
        print("Bluetooth Resetting")
        break
    case .unknown:
        print("Bluetooth Unknown")
        break
    default:
        break
    }
}

}

这段代码会创建一个新的CBCentralManager对象,用于管理蓝牙的连接和断开。这个对象将使用CBCentralManagerOptionRestoreIdentifierKey选项

相关内容

热门资讯

玩家亲测!天天真人麻将有挂吗(... 玩家亲测!天天真人麻将有挂吗(辅助挂)真是是真的有挂(2021已更新)(哔哩哔哩)1、天天真人麻将有...
九分钟了解!永州同城跑胡子合集... 九分钟了解!永州同城跑胡子合集有外 挂吗,友乐广西麻将有挂的吗,曝光教程(有挂方法)所有人都在同一条...
推荐一款!边锋老友斗地主挂怎么... 推荐一款!边锋老友斗地主挂怎么能买到(透视辅助)总是真的有挂(2021已更新)(哔哩哔哩)1、金币登...
7分钟了解!江苏连云港大宝麻将... 7分钟了解!江苏连云港大宝麻将软件靠谱吗,双喜大厅辅助,2025新版教程(有挂秘籍)1、实时江苏连云...
玩家实测!福建老友棋牌有挂吗(... 玩家实测!福建老友棋牌有挂吗(辅助挂)确实存在有挂(2021已更新)(哔哩哔哩)1)福建老友棋牌有挂...
3分钟了解!家家乐牌吧可以开挂... 3分钟了解!家家乐牌吧可以开挂吗,一起宁德钓蟹黑科技,扑克教程(有挂详情)1、每一步都需要思考,不同...
安装程序教程!网易茶馆有辅助(... 安装程序教程!网易茶馆有辅助(透明挂)果然真的有挂(2021已更新)(哔哩哔哩)1、网易茶馆有辅助a...
三分钟了解!哈灵麻将攻略小,雀... 三分钟了解!哈灵麻将攻略小,雀神广东麻将助赢神器,AI教程(有挂科普);1、在雀神广东麻将助赢神器a...
今日焦点!喜扣打筒子四喜外挂(... 今日焦点!喜扣打筒子四喜外挂(透视)总是是有挂(2020已更新)(哔哩哔哩)1、玩家可以在喜扣打筒子...
四分钟了解!多乐跑得快有挂吗,... 四分钟了解!多乐跑得快有挂吗,全民如意棋牌有挂吗,分享教程(有挂插件)1、用户打开应用后不用登录就可...