IOS游戏中心GKLocalPlayerListener

我试图在回合制游戏中实现一个事件监听器,所以玩家可以在轮到他时或朋友邀请时接收事件。 GKTurnBasedEventHandler在IOS 7中被弃用,我读了我应该使用GKLocalPlayerListener的文档; 但这是它的延伸。 有没有人使用过它,因为没有任何信息。

这是我之前所尝试的,它不起作用。

- (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"); } 

这是我用来注册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]); } }; 

该文档指出,您只应该注册一次GKLocalPlayerEventListener,以便通过检查您是否已经注册来改进此代码。

请注意, authenticateWithCompletionHandler在iOS 6中已弃用,他们build议像上面那样设置authenticateHandler属性。

我相信你在那里。 就在这个时候做几件事情。 确保在添加侦听器之前不要添加多个侦听器,只需注销所有侦听器即可。

我确定我在整个项目中只做过一次,但是我多次得到本地玩家。

 -(void) onLocalPlayerAuthChanged:(GKLocalPlayer*)authPlayer { [authPlayer unregisterAllListeners]; [authPlayer registerListener:_Whatever_]; } 

我可能会晚一点,但希望它会帮助那里的人…

这就是我所做的。 根据苹果的文档,我创build[我]自己的方法,显示适当的[我]应用程序的身份validation视图。

  - (void)authenticateLocalUser { if ([GKLocalPlayer localPlayer].authenticated == NO) { __weak typeof(self) weakSelf = self; __weak GKLocalPlayer *weakPlayer = [GKLocalPlayer localPlayer]; weakPlayer.authenticateHandler = ^(UIViewController *viewController, NSError *error) { if (viewController != nil) { [weakSelf showAuthenticationDialogWhenReasonable:viewController]; } else if (weakPlayer.isAuthenticated) { // Player has been authenticated! [weakPlayer registerListener:weakSelf]; } else { // Should disable Game Center? } }; } else { // Already authenticated [[GKLocalPlayer localPlayer] registerListener:self]; } } -(void)showAuthenticationDialogWhenReasonable:(UIViewController *)controller { [[[[[UIApplication sharedApplication] delegate] window] rootViewController] presentViewController:controller animated:YES completion:nil]; } 

这段代码在单例帮助器类中,如果你在自己的类中有它,它可能会被简化。