Swift在背景中发射线程

时间:2016-08-07 20:28:25

标签: ios multithreading swift2

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

let qualityOfServiceClass = QOS_CLASS_BACKGROUND
let backgroundQueue = dispatch_get_global_queue(qualityOfServiceClass, 0)

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

但是这个类只是在前景中开始处理...有什么想法吗?

EDIT1:

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

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()
  }

当应用程序启动并保持在前台时,每次扫描都会正确执行" delayPolling"秒。 但是只要我的应用程序是背景,扫描就会暂停。只有当它再次回到前台时它才会重新启动。

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

EDIT2:

阅读文档https://developer.apple.com/library/ios/documentation/NetworkingInternetWeb/Conceptual/CoreBluetooth_concepts/CoreBluetoothBackgroundProcessingForIOSApps/PerformingTasksWhileYourAppIsInTheBackground.html

我可以看到

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

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

enter image description here

但是我的应用程序没有在后台运行我的帖子。

1 个答案:

答案 0 :(得分:3)

我意识到这是一个古老的问题,但是在后台扫描需要您提供服务UUID。

central.scanForPeripheralsWithServices(nil, options: nil)

需要成为

central.scanForPeripheralsWithServices(serviceUUID, options: nil)