首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >后台快速启动线程

后台快速启动线程
EN

Stack Overflow用户
提问于 2016-08-07 20:28:24
回答 1查看 726关注 0票数 4

我试图使用以下代码在后台线程中发送进程:

代码语言:javascript
复制
let qualityOfServiceClass = QOS_CLASS_BACKGROUND
let backgroundQueue = dispatch_get_global_queue(qualityOfServiceClass, 0)

dispatch_async(backgroundQueue, {
    print("running in the background queue")
    btDiscovery
})

但是这个类只是在foreground...any思想开始的时候进行处理吗?

EDIT1:

btDiscovery是一个类,它每隔X秒执行一次BLE设备扫描:

代码语言:javascript
复制
let btDiscoverySharedInstance = Beacon();

class Beacon: NSObject, CBCentralManagerDelegate {

private var centralManager: CBCentralManager?
private var peripheralBLE: CBPeripheral?
....


   func centralManagerDidUpdateState(central: CBCentralManager) {
    switch (central.state) {
    case CBCentralManagerState.PoweredOff:
        print("BLE powered off")
        self.clearDevices()

    case CBCentralManagerState.Unauthorized:
        // Indicate to user that the iOS device does not support BLE.
        print("BLE not supported")
        break

    case CBCentralManagerState.Unknown:
        // Wait for another event
        print("BLE unknown event")
        break

    case CBCentralManagerState.PoweredOn:
        print("BLE powered on")
            self.startScanning()
        break

    case CBCentralManagerState.Resetting:
        print("BLE reset")
        self.clearDevices()

    case CBCentralManagerState.Unsupported:
        print("BLE unsupported event")
        break
    }
}


    func startScanning() {
    print("Start scanning...")
        if let central = centralManager {
            central.scanForPeripheralsWithServices(nil, options: nil)
        }
    }

  func centralManager(central: CBCentralManager, didDiscoverPeripheral peripheral: CBPeripheral, advertisementData: [String : AnyObject], RSSI: NSNumber) {
    print("Discovered peripheral \(RSSI) dBM name: \(peripheral.name)")
    print("UUID: \(peripheral.identifier.UUIDString)")
    ...
    sleep(delayPolling)
    self.startScanning()
  }

当应用程序被启动并保持在前台时,每隔一秒钟就会正确地执行扫描。但一旦我把我的应用程序是背景,扫描暂停。只有在前景再次出现时,它才会重新启动。

每次我都需要在后台运行此扫描(即使我们为这个线程设置了较低的优先级)。

EDIT2:

通过阅读文档concepts/CoreBluetoothBackgroundProcessingForIOSApps/PerformingTasksWhileYourAppIsInTheBackground.html

我看得出来

当实现中心角色的应用程序在其UIBackgroundModes文件中包含具有蓝牙中心值的Info.plist键时,核心蓝牙框架允许您的应用程序在后台运行以执行特定的蓝牙相关任务。当您的应用程序处于后台时,您仍然可以发现并连接到外围设备,并探索外围数据并与其进行交互。此外,当调用任何CBCentralManagerDelegate或CBPeripheralDelegate委托方法时,系统会唤醒应用程序。

我在我的Info.plist文件中选择了相应的选项:

但我的应用程序并没有在后台运行我的线程。

EN

回答 1

Stack Overflow用户

发布于 2019-03-14 16:32:47

我意识到这是一个老问题,但是在后台进行扫描需要您提供一个Service。

代码语言:javascript
复制
central.scanForPeripheralsWithServices(nil, options: nil)

需要的是

代码语言:javascript
复制
central.scanForPeripheralsWithServices(serviceUUID, options: nil)
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38818250

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档