Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run swift code on main thread in react-native

I am trying to make a react-native app cast to chromecast. The chromecast GCKDeviceScanner has to run on the main thread.

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? 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?

like image 838
tbergq Avatar asked Nov 25 '25 18:11

tbergq


1 Answers

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 { .. }.

Old version, before Swift 4 (maybe even 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
  }
}
like image 52
hnh Avatar answered Nov 27 '25 09:11

hnh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!