在应用程序的Info.plist文件中添加一些键值对,允许BLE在应用程序被推送到后台时继续操作。
Privacy - Bluetooth Always Usage Description Privacy - Bluetooth Peripheral Usage Description
键值对的值应该是一个字符串,用于描述应用程序需要使用蓝牙的原因。
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) }
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
选项
下一篇:BLE制造广告数据