How would I authenticate Game Center and local player in my app? I am trying to add achievements, but the whole “authentication” part is very confusing to me.
Authenticate game Center
You can authenticate by using a method along the following lines (in the GameCenterHelp that will be a singleton):
So, in your GameScene class you may have something like:
Code Block func authenticatePlayer() { GKLocalPlayer.local.authenticateHandler = { gcAuthVC, error in // In your delegate, implement method `didChangeAuthStatus`, for example to enable a Game Center button self.delegate?.didChangeAuthStatus(isAuthenticated: GKLocalPlayer.local.isAuthenticated) // This is called if the local player gets authenticated. Nothing happens, GKLocalPlayer gets registered if GKLocalPlayer.local.isAuthenticated { GKLocalPlayer.local.register(self) } // This is called, when a player opens your app and he|she is not authenticated. // It opens a viewController with sign-in info else if let vc = gcAuthVC { self.delegate?.presentGameCenterAuth(viewController: vc) } // Handing an error while authenticating else { print(">>>>> Error authenticating the Player! \(error?.localizedDescription ?? "none") <<<<<") } }
So, in your GameScene class you may have something like:
Code Block override func didMove(to view: SKView) { GameCenterHelper.sharedInstance.delegate = self GameCenterManager.sharedInstance.authenticatePlayer() } @objc func didChangeAuthStatus(isAuthenticated: Bool) { ... For example, stop spinning activity indicator if indicator != nil { indicator!.stop() indicator!.removeFromSuperview() indicator = nil } ... Or enable the *PLAY ON GAMECENTER* button if GKLocalPlayer.local.isAuthenticated { btnPlayGameCenter.setButtonLabel(title: btnPlayGameCenterTitle(), font: "Noteworthy-Bold", fontSize: 40) } /** Present the view controller with the Sign-in info */ func presentGameCenterAuth(viewController: UIViewController?) { guard let vc = viewController else {return} self.view!.window?.rootViewController?.present(vc, animated: true) }
Thanks. Would that work with a swiftUI single view app, or just with a SpriteKit app?
That should work with any kind of app. It is only a matter where you call authenticatePlayer() and assign the delegate: in didMove(view:) or viewDidLoad() or whatever SwiftUI initial method is (I am old school).
Ok thanks
No worries. Please feel free to upvote my response if it works. Cheers.
Sorry, but I have one more question. Where would I put the code? In contentview.swift, appdelegate.swift, or scenedelegate.swift?
Which code? Method authenicatePlayer()? For this, you need to have a separate class that will handle all you GameKit methods. Google "raywenderlich gamecenter tutorials" (a tutorial on building a turn-based game has code in Swift).
Or where to call GameCenterHelper.sharedInstance.authenticatePlayer?
Or where to call GameCenterHelper.sharedInstance.authenticatePlayer?
Never mind I figured it out thanks for all your help!