How can I use Game Center or the GameKit Framework with a Sprite Kit Xcode template? In Sprite kit, it uses Scenes; but normally to view the leaderboards for example you need to "presentModalViewController" but that is not possible in SKView.
And how can I authenticate the player and all that other fun stuff in iOS 6.
Thanks in advance!
you can authenticate like this
[[GKLocalPlayer localPlayer] authenticateWithCompletionHandler:^(NSError *error) {
if (error == nil)
{
static_setEnable( true );
NSLog(@" Authenticate local player complete");
}
else
{
static_setEnable( false );
NSLog(@"Authenticate local player Error: %@", [error description]);
}
}];
}
You can use "presentModalViewController" by using this code to access the root view controller
UIViewController *vc = self.view.window.rootViewController;
[vc presentViewController: gameCenterController animated: YES completion:nil];
Now you can access your ModelViewController anywhere include in SKScenes. I did it in my newest game and it worked well
Besides, I suggest you use the separate object to control game center like leaderboard and achievement so you can reuse it in your next game.
Here is an updated authenticate local player, but Ravindra's code also works.
- (void) authenticateLocalPlayer
{
GKLocalPlayer *localPlayer = [GKLocalPlayer localPlayer];
localPlayer.authenticateHandler = ^(UIViewController *viewController, NSError *error){
if (viewController != nil)
{
//showAuthenticationDialogWhenReasonable: is an example method name. Create your own method that displays an authentication view when appropriate for your app.
//[self showAuthenticationDialogWhenReasonable: viewController];
}
else if (localPlayer.isAuthenticated)
{
//authenticatedPlayer: is an example method name. Create your own method that is called after the loacal player is authenticated.
//[self authenticatedPlayer: localPlayer];
}
else
{
//[self disableGameCenter];
}
};
}
Swift 2.0
func authenticateLocalPlayer() {
let localPlayer = GKLocalPlayer.localPlayer()
localPlayer.authenticateHandler = { (viewController, error ) -> Void in
if (viewController != nil) {
let vc:UIViewController = self.view!.window!.rootViewController!
vc.presentViewController(viewController!, animated: true, completion:nil)
} else {
print ("Authentication is \(GKLocalPlayer.localPlayer().authenticated) ")
GlobalData.loggedIntoGC = true
// do something based on the player being logged in.
GlobalData Swift File:
static var loggedIntoGC:Bool = false
Call Method in your scene where Game Center is being enabled: ie HUD or GameScene in the
override func didMoveToView(view: SKView)`
authenticateLocalPlayer()
来源:https://stackoverflow.com/questions/19473739/game-center-integration-with-sprite-kit