Search code examples
authenticationgame-centerviewdidloadswift4.2

Delay GameCenter Authentication View Controller from being presentation - Swift 4.2


I am trying to make the GameCenter Authentication View Controller be delayed 2 seconds before being presented. There are about 2 seconds of button animations that take place in my VC and I don't want them to be blocked by the presentation of the GameCenter Authentication View Controller. Any suggestions?

override func viewDidLoad() {
    super.viewDidLoad()

     // Game Center - Authentication of player
     NotificationCenter.default.addObserver(self, selector: #selector(showAuthenticationViewController), name: NSNotification.Name(GameKitHelper.PresentAuthenticationViewController), object: nil)

     GameKitHelper.sharedInstance.authenticateLocalPlayer()
}

// Game Center - Presents authentication view controller
@objc func showAuthenticationViewController() {
    let gameKitHelper = GameKitHelper.sharedInstance
    if let authenticationViewController =
        gameKitHelper.authenticationViewController {
        self.present(authenticationViewController, animated: true, completion: nil)
    }

}

// add this to deregister for notifications when the object is deallocated
deinit {
    NotificationCenter.default.removeObserver(self)
}

Solution

  • Perhaps, good old Grand Central Dispatch (GCD) will get the job done. The 2.0 is for 2 seconds, but change it to however long you need.

    override func viewDidLoad() {
        super.viewDidLoad()
    
        DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) {
    
             // Game Center - Authentication of player
            NotificationCenter.default.addObserver(self, selector: #selector(self.showAuthenticationViewController), name: NSNotification.Name(GameKitHelper.PresentAuthenticationViewController), object: nil)
    
            GameKitHelper.sharedInstance.authenticateLocalPlayer()
        }
    }