Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

Daniel Bessonov
Daniel Bessonov
1,413 Points

Game Center Authentication in Swift: More than Once

My code is as follows:

func authenticateLocalPlayer() { 
    let localPlayer: GKLocalPlayer = GKLocalPlayer.localPlayer()
    localPlayer.authenticateHandler = {(ViewController, error) -> Void      in
        if((ViewController) != nil) {
            self.presentViewController(ViewController, animated: true, completion: nil)
        } else if (localPlayer.authenticated) {
            print("Local player already authenticated")
            self.gcEnabled = true
            if self.gcEnabled == true {
                self.showLeaderboard()
                self.activity.stopAnimating()
            }
            // Get the default leaderboard ID
            localPlayer.loadDefaultLeaderboardIdentifierWithCompletionHandler({ (leaderboardIdentifer: String!, error: NSError!) -> Void in
                if error != nil {
                    println(error)
                } else {
                    self.gcDefaultLeaderBoard = leaderboardIdentifer
                }
            })
        }

            else {
                self.gcEnabled = false
                print("Local player could not be authenticated, disabling game center")
                print(error)
                if((ViewController) != nil) {
                self.presentViewController(ViewController, animated: true, completion: nil)
            }

        } } }  

func showLeaderboard() {

    let gcVC: GKGameCenterViewController = GKGameCenterViewController()
    gcVC.gameCenterDelegate = self
    gcVC.viewState = GKGameCenterViewControllerState.Leaderboards
    gcVC.leaderboardIdentifier = leaderboardIdentifier
    self.presentViewController(gcVC, animated: true, completion: nil)
}

This code works perfectly fine the first time my leaderboard button is clicked (in which I use an @IBAction and just call this function), however, if I am prompted to log in and I click "cancel", and then click the button again, it does not work. (meaning the log in page does not appear). Any ideas? Thanks for your help!