编写苹果游戏中心应用程序(翻译 1.5 在游戏中心验证本地玩家)

来源:互联网 发布:奥点云 vs 阿里云 编辑:程序博客网 时间:2024/04/28 09:33
 

1.5 在游戏中心验证本地玩家

问题

    你知道使用游戏中心功能的第一步是验证本地玩家,但你不知道如何去做。

解决方案

    使用GKLocalPlayer类的authenticateWithCompletionHandler:实例方法。

讨论

    在游戏中心,每件事都依赖于访问本地玩家这个简单的能力。本地玩家通过iOS设备上的游戏中心应用程序或使用了游戏中心的iOS应用程序验证进入游戏中心。

    如果玩家自己还没有通过验证,则试图获取本地玩家时,会首先提示玩家进行验证。如果玩家取消,我们在代码中将收到一个错误。如果玩家已经验证通过,就不会有提示;并且我们可以获得他的玩家对象。

    游戏中心的每个玩家都用GKPlayer对象表示。本地玩家也是一个玩家,不过但使用GKLocalPlayer类型的对象表示。它是GKPlayer的子类。为取得本地玩家对象的引用,你可以使用GKLocalPlayer的类方法localPlayer,象下面这样:

        GKLocalPlayer *localPlayer = [GKLocalPlayer localPlayer];

    拥有本地玩家对象后,你必须,只要你有能力这样做(就在应用程序加载后),使用GKLocalPlayer类的实例方法authenticateWithCompletionHandler:验证玩家。该方法接受一个块对象(该块对象不能有返回值,还应当接受单独的一个NSError类型的参数;该参数将保存验证过程中发生的任何错误):

        - (void) authenticateLocalPlayer{

            GKLocalPlayer *localPlayer = [GKLocalPlayer localPlayer];

            [localPlayer authenticateWithCompletionHandler:^(NSError *error) {

                if (error == nil){
                    NSLog(@"Successfully authenticated the local player.");
                } else {
                    NSLog(@"Failed to authenticate the player with error = %@", error);
                }
            }];
        }

    如果玩家还没有登录到游戏中心,则在该代码执行后,会被弹出对话框提示要求登录,如图1-8所示。


图 1-8 游戏中心,要求本地玩家登录

    如果本地玩家已经通过验证,GKLocalPlayer类的实例方法isAuthenticated将返回YES,否则返回NO。因此,为提高验证的方法,我们可以把它添加到代码中:

       - (void) authenticateLocalPlayer{

         GKLocalPlayer *localPlayer = [GKLocalPlayer localPlayer];

          if ([localPlayer isAuthenticated] == YES){
            NSLog(@"The local player has already authenticated.");
            return;
         }

         [localPlayer authenticateWithCompletionHandler:^(NSError *error) {
            if (error == nil){
               NSLog(@"Successfully authenticated the local player.");
            } else {
               NSLog(@"Failed to authenticate the player with error = %@", error);
            }
         }];
      }

    我们调用GKLocalPlayer类的实例方法isAuthenticated以避免对玩家的一遍又一遍的验证。没有这个检查也不会骚扰到玩家(如果他已经登录到游戏中心的话)。但作这个检查可以节省对游戏中心的过度调用。

    现在,知道了如何验证本地玩家,是时候开始游戏中心中更加复杂的主题了。

原创粉丝点击