1

Im working with ReplayKit and when I press the cancel or save button it dismisses the view controller and I would like to show an ad. The problem is that the ad doesn't show up and I get this error: How do I fix it? Thanks!

Warning: Exception caught during invocation of received message, dropping incoming message and invalidating the connection. Exception: This method must be called on the main thread

internal func previewControllerDidFinish(previewController: RPPreviewViewController) {

previewViewController.dismissViewControllerAnimated(true, completion: nil)

NSNotificationCenter.defaultCenter().postNotificationName("loadAd", object: nil)

}
coding22
  • 689
  • 1
  • 7
  • 28
  • Exception: This method must be called on the main thread. You can dispatch the function with the main thread using GCD. By the way user interface must be updated with the main thread. – Muhammad Zeeshan Jul 27 '16 at 04:46
  • For Swift 3 use `DispatchQueue.main.async { // put your code here }` – Tarsem Singh Jan 26 '17 at 07:03

1 Answers1

3

All UI related operations must be done on the main thread. You could do something like this using GCD:

dispatch_async(dispatch_get_main_queue()) {
        previewViewController.dismissViewControllerAnimated(true, completion: nil)
}

You could also post the notification in the completion block of dismissViewControllerAnimated

batman
  • 1,937
  • 2
  • 22
  • 41
  • I get this error now: Warning: Attempt to present on whose view is not in the window hierarchy! – coding22 Jul 27 '16 at 17:08
  • I had to add a 2 sec timer after I dismissed the viewcontroller to show the ad and it worked. IT wouldnt allow me to call the ad right after I closed the replay kit window for some reason. – coding22 Jul 27 '16 at 17:35
  • 2 seconds delay is quite a lot actually, try with something lower like 0.2 or 0.5s for a more seamless experience. Or whatever works for you :) – batman Jul 28 '16 at 02:11