Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IOS Game Center GKLocalPlayerListener

I was trying to implement an event listener in a turn based game so a player can receive when his turn is active or when he is invited by a friend. GKTurnBasedEventHandler is deprecated in IOS 7 and i read in the documentation that i should use GKLocalPlayerListener; but that's the extend of it. Is there someone who used it already, because there is no info anywhere.

This is what i tried before, and it does not work.

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    GKLocalPlayer *localPlayer = [GKLocalPlayer localPlayer];
    [localPlayer authenticateWithCompletionHandler:^(NSError *error)
     {
         if (localPlayer.isAuthenticated)
         { 
             GKLocalPlayer *localPlayer = [GKLocalPlayer localPlayer];
             [localPlayer registerListener:self];
         }
     }];

    return YES;
}

-(void)handleInviteFromGameCenter:(NSArray *)playersToInvite
{
    NSLog(@"test");
}

- (void)player:(GKPlayer *)player receivedTurnEventForMatch:(GKTurnBasedMatch *)match didBecomeActive:(BOOL)didBecomeActive
{
    NSLog(@"test");
}
like image 839
Macaret Avatar asked Oct 18 '13 06:10

Macaret


2 Answers

Here is some code that I use in order to register GKLocalPlayerListener

__weak GKLocalPlayer *localPlayer = [GKLocalPlayer localPlayer];
localPlayer.authenticateHandler = ^(UIViewController *viewController, NSError *error) {
   if (viewController) {
         [authenticateFromViewController presentViewController:viewController animated:YES completion:^{
          [localPlayer registerListener:self];
          NSLog(@"Authenticated. Registering Turn Based Events listener");
        }];
  } else if (localPlayer.authenticated) {
         [localPlayer registerListener:self];
         NSLog(@"User Already Authenticated. Registering Turn Based Events listener");
  } else {
         NSLog(@"Unable to Authenticate with Game Center: %@", [error localizedDescription]);
  }
};

The documentation states that you should only register for an GKLocalPlayerEventListener once so you could improve this code by checking if you've already registered.

Note that authenticateWithCompletionHandler is deprecated in iOS 6 and they recommend setting the authenticateHandler property like I did above.

like image 72
aahrens Avatar answered Sep 21 '22 15:09

aahrens


I believe you were there. Just this time do a couple of things. Make sure you dont add multiple listeners also before you add a listener, just incase unregister all listeners.

I made sure I only did this once in my whole project, but I get the local player multiple times.

-(void) onLocalPlayerAuthChanged:(GKLocalPlayer*)authPlayer {

    [authPlayer unregisterAllListeners];
    [authPlayer registerListener:_Whatever_];

}
like image 45
tomJ Avatar answered Sep 18 '22 15:09

tomJ