How to avoid Game Center authentication repeating

2019-07-28 16:33发布

Game Kit stores a strong reference to the completion handler that I send to authenticateWithCompletionHandler:, which means that each time the user exits and enters the app, it gets called again. This makes sense, but it causes a problem with a use case I have:

1) I prompt the user to log into Game Center when the app launches.

2) They tap Cancel because they want to play single player for a while. Therefore they are not logged in.

3) At some point, they decide they want to play online, so they tap my "Play Online" button.

4) This ought to show a screen where they can set up online game options, etc, but I notice they have no authenticated player, so…

5) I prompt the user again to log in to Game Center.

6) The user logs in this time, and in the completion handler I show my online game options screen.

Step 6 is the where the problem lies: every time the user leaves and re-enters the app, it will show my game options screen, because my completion handler is repeated. If I take out the code in the completion handler to show the online game options, the user has to tap the button twice - once to login, and once again to show the online options.

What is the smart solution to this?

For reference, a simplified version of my code looks like this:

- (IBAction)playOnlineTapped:(id)sender
{
    GKLocalPlayer *localPlayer = [GKLocalPlayer localPlayer];
    [localPlayer authenticateWithCompletionHandler:^(NSError *error) {
    if (localPlayer.authenticated) {
            [self showOnlineGameOptions];
    }
    }];
}

So many of the examples I have read assume that the user logs in first time, but I don't think that's always going to be the case.

Thanks in advance for your help!

标签: ios gamekit
1条回答
淡お忘
2楼-- · 2019-07-28 17:02

One solution to this would be to not have the completion handler change your views. This seems like an odd idea because the completion handler is called asynchronously and could happen any time after you request authentication.

Instead, the completion handler could check if you are in the online menu and enable buttons for you. Until then, have these buttons disabled and show a message saying "waiting for Game Center". The key is not to trigger any scene transitions in your completion handler. That would be bad design because you don't know when this block is called.

Another hint. If the user declines to log in to Game Center, your authentication request at some point won't prompt the user. If I remember right, you will receive GKErrorUserDenied immediately. Therefore, you should tell users that they can launch your game from within the Game Center app.

查看更多
登录 后发表回答