【问题标题】:Asynchronous Swift issues异步 Swift 问题
【发布时间】:2018-12-08 03:19:13
【问题描述】:

我是一名使用 Swift 的 Javascript 开发人员,我很难将我找到的示例 Playground 应用程序 (https://github.com/gregiOS/Playgrounds/tree/master/BLE.playground) 迁移到 CLI 应用程序。

import Cocoa
import PlaygroundSupport

let tableViewController = TableViewController()
let dataSource = tableViewController.dataSource

PlaygroundPage.current.liveView = tableViewController.view

let scanner = BluetoothScanner { scanner in
    scanner.startScanning { (peripheral) in
        print("Discovered peripheral: \(peripheral.tableViewData)")
    }
}

我的愿望和我尝试的只是删除 import PlaygroundSupportdataSource/tableViewController 东西,然后将外围设备打印到标准输出,但是程序会立即退出。我尝试使用调度组,但这似乎也不起作用:

import Cocoa

let myGroup = DispatchGroup()

print("Scanning...")
myGroup.enter()

let scanner = BluetoothScanner { scanner in
  scanner.startScanning { (peripheral) in
    print("Discovered peripheral: \(peripheral.tableViewData)")
    myGroup.leave()
  }
}

myGroup.notify(queue: .main) {
  print("Finished all requests.")
}

还尝试使用myGroup.wait(),但它只是坐在那里无所事事。我相信问题的一部分是扫描无限期地运行,而我只需要它运行 2 秒左右然后停止。

重点是,我想不通,需要创建一个显示蓝牙发现的 PoC。我将不胜感激。

【问题讨论】:

    标签: swift core-bluetooth


    【解决方案1】:

    要在 CLI 中运行异步内容,您需要一个 runloop

    let runLoop = CFRunLoopGetCurrent()
    print("Scanning...")
    
    let scanner = BluetoothScanner { scanner in
      scanner.startScanning { (peripheral) in
        print("Discovered peripheral: \(peripheral.tableViewData)")
        CFRunLoopStop(runLoop)
      }
    }
    
    CFRunLoopRun()
    

    【讨论】:

      【解决方案2】:

      除了vadian's answer,您不一定需要运行循环,除非您的代码使用需要运行循环的结构(例如Timer)。

      您也可以在程序结束时调用dispatchMain 来启动Dispatch systemdispatchMain 永远不会返回,所以你需要调用exit(0) 或类似的方法在适当的地方退出程序:

      import Dispatch
      
      let myGroup = DispatchGroup()
      
      print("Scanning...")
      myGroup.enter()
      
      let scanner = BluetoothScanner { scanner in
        scanner.startScanning { (peripheral) in
          print("Discovered peripheral: \(peripheral.tableViewData)")
          myGroup.leave()
        }
      }
      
      myGroup.notify(queue: .main) {
        print("Finished all requests.")
        exit(0)
      }
      
      dispatchMain()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-12-09
        • 2017-12-31
        • 1970-01-01
        • 2010-12-16
        • 2014-10-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多