简体   繁体   English

在 react-native 的主线程上运行 swift 代码

[英]Run swift code on main thread in react-native

I am trying to make a react-native app cast to chromecast.我正在尝试将 react-native 应用程序转换为 chromecast。 The chromecast GCKDeviceScanner has to run on the main thread. chromecast GCKDeviceScanner 必须在主线程上运行。

The react native page says to run on main thread you have to do this:反应本机页面说要在主线程上运行,您必须这样做:

 - (dispatch_queue_t)methodQueue { return dispatch_get_main_queue(); }

I am not very familiar with swift or ios, so where do I put this code, and how do I use it?我对 swift 或 ios 不是很熟悉,所以我把这段代码放在哪里,我如何使用它? I have my method:我有我的方法:

 let filterCriteria = GCKFilterCriteria(forAvailableApplicationWithID: "myApp") let deviceScanner = GCKDeviceScanner(filterCriteria: filterCriteria) if let deviceScanner = deviceScanner { deviceScanner.addListener(self) deviceScanner.startScan() deviceScanner.passiveScan = true }

Any idea on how I can run my code on the main thread?关于如何在主线程上运行我的代码的任何想法?

To run that code section in the main thread, you can do this:要在主线程中运行该代码部分,您可以这样做:

DispatchQueue.main.async {
  let filterCriteria = GCKFilterCriteria(forAvailableApplicationWithID: "myApp")
  
  let deviceScanner = GCKDeviceScanner(filterCriteria: filterCriteria)
  if let deviceScanner = deviceScanner {
    deviceScanner.addListener(self)
    deviceScanner.startScan()
    deviceScanner.passiveScan = true
  }
}

Another option is RunLoop.main.perform { .. } .另一种选择是RunLoop.main.perform { .. }

Old version, before Swift 4 (maybe even 3?):旧版本,在 Swift 4 之前(甚至可能是 3?):

dispatch_async(dispatch_get_main_queue()) {
  let filterCriteria = GCKFilterCriteria(forAvailableApplicationWithID: "myApp")
  
  let deviceScanner = GCKDeviceScanner(filterCriteria: filterCriteria)
  if let deviceScanner = deviceScanner {
    deviceScanner.addListener(self)
    deviceScanner.startScan()
    deviceScanner.passiveScan = true
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM