KickerKeeper
KickerKeeper

Reputation: 265

Navigating in NSNotificationCenter callback has long delay iOS Swift

I am trying to navigate within a callback on a NSNotificationCenter observer. I can see the callback being hit when debugging, but the navigation doesn't happen in the UI until much later (~30 sec). Am I going about this wrong? I would imagine this use case is pretty common - Navigate when some background event has happened.

override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)

    let storyboard = self.storyboard
    let vc: UIViewController = storyboard.instantiateViewControllerWithIdentifier("homeViewController") as UIViewController

    NSNotificationCenter.defaultCenter().addObserverForName("ItemsLoaded", object: nil, queue: nil, usingBlock: { note in

        self.navigationController.pushViewController(vc, animated: true)

    })
}

Upvotes: 2

Views: 821

Answers (1)

KickerKeeper
KickerKeeper

Reputation: 265

I was able to find the answer. Looks like I needed to dispatch the posting of the notification on the main thread. It works, just not sure if this is the best approach yet.

dispatch_async(dispatch_get_main_queue(), {
    NSNotificationCenter.defaultCenter().postNotificationName("ItemsLoaded", object: nil)
})

Upvotes: 1

Related Questions