[英]iOS Bluetooth Low Energy Scan in Background (swift3)
我实际上正在开发使用Swift3编写的iOS上的Bluetooth Low Energy应用程序。
当我与CoreBluetooth处于前台(扫描,连接,交换数据..)时,我的应用程序运行良好,而我希望它在后台运行(第一步是在后台扫描外围设备)。
我已阅读了有关该主题的文章,因此我已经为BLE添加了背景模式(我添加了所有背景模式,所以问题不存在)。
因此,在我的代码中,当我输入applicationDidEnterBackground
方法时,我将调用initCBCentralManager
方法。 这很好,因为它随后进入了centralManagerDidUpdateState
并处于“ centralManagerDidUpdateState
”状态。 我的scan
函数被调用,所以这不是问题。
但是,在调用scan
方法之后,什么也没发生,我再也没有得到didDiscover peripheral
调用。 当我在前台使用这些函数时(通过在applicationWillEnterForeground
而不是applicationDidEnterBackground
调用我的函数),它可以工作,但在后台时不起作用。
我读到我需要发现一个特定的服务,这就是我要做的事(我的服务是6E400001-B5A3-F393-E0A9-E50E24DCCA9E
,并且CBCentralManagerScanOptionAllowDuplicatesKey
选项将被忽略,但是如果我将其更改为false,则不会发生任何事情。
那么,当我进入后台时如何扫描低功耗蓝牙外围设备?
这是我的代码:
import CoreBluetooth
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, CBPeripheralDelegate, CBCentralManagerDelegate {
var _manager : CBCentralManager?
func applicationDidEnterBackground(_ application: UIApplication) {
initCBCentralManager()
}
func initCBCentralManager() {
var dic : [String : Any] = Dictionary()
dic[CBCentralManagerOptionShowPowerAlertKey] = false
_manager = CBCentralManager(delegate: self, queue: nil)
}
public func centralManagerDidUpdateState(_ central: CBCentralManager) {
switch central.state {
case .poweredOff:
print("State : Powered Off")
case .poweredOn:
print("State : Powered On")
scan()
case .resetting:
print("State : Resetting")
case .unauthorized:
print("State : Unauthorized")
case .unknown:
print("State : Unknown")
case .unsupported:
print("State : Unsupported")
}
}
func scan()
{
print("SCAN")
let service = "6E400001-B5A3-F393-E0A9-E50E24DCCA9E"
var service_cbbuid:[CBUUID] = [CBUUID(string: service)]
_manager?.scanForPeripherals(withServices: service_cbbuid, options: [CBCentralManagerScanOptionAllowDuplicatesKey:true])
}
func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
print("BACKGROUND_SCAN -> \(peripheral.name.unsafelyUnwrapped) \(RSSI)dBm")
}
请参阅iPhoneAppProgrammingGuide的“背景执行”部分。 简而言之,您的应用必须是以下类型之一:
并且,您必须按如下所示将其添加到Info.plist:将UIBackgroundModes键添加到Info.plist文件,并将其值设置为包含以下一个或多个字符串的数组:
位置-该应用程序即使在后台运行,也可以使用户知道其位置。
voip-该应用程序使用户能够使用Internet连接拨打电话。
报亭内容-该应用程序是一个报亭应用程序,可在后台下载和处理杂志或报纸的内容。
外部附件-该应用程序与硬件附件一起使用,需要通过外部附件框架定期提供更新。
请注意,审核过程的一部分将进行检查,以确保您的应用程序执行了其在后台处理方面所做的工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.