编写苹果游戏中心应用程序(翻译 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以避免对玩家的一遍又一遍的验证。没有这个检查也不会骚扰到玩家(如果他已经登录到游戏中心的话)。但作这个检查可以节省对游戏中心的过度调用。
现在,知道了如何验证本地玩家,是时候开始游戏中心中更加复杂的主题了。
- 编写苹果游戏中心应用程序(翻译 1.5 在游戏中心验证本地玩家)
- 编写苹果游戏中心应用程序(翻译 1.6 获取本地玩家的信息)
- 编写苹果游戏中心应用程序(翻译 1.8 获取本地玩家的好友信息)
- 编写苹果游戏中心应用程序(翻译 1.18 在多人游戏中处理玩家的状态变更)
- 编写苹果游戏中心应用程序(翻译 1.7 在游戏中心添加朋友)
- 编写苹果游戏中心应用程序(翻译 1.12 向玩家显示排行榜)
- 编写苹果游戏中心应用程序(翻译 1.16 向玩家显示成就)
- 编写苹果游戏中心应用程序(翻译 1.3 为iOS应用程序设置游戏中心)
- 编写苹果游戏中心应用程序(翻译 1.2 创建游戏中心账户)
- 编写苹果游戏中心应用程序(翻译 1.14 向游戏中心提交成就)
- 编写苹果游戏中心应用程序(翻译 1.9 在iTunes Connect中创建排行榜)
- 编写苹果游戏中心应用程序(翻译 1.13 在iTunes Connect中创建成就)
- 编写苹果游戏中心应用程序(翻译 1.4 添加游戏工具包框架)
- 编写苹果游戏中心应用程序(翻译 1.17 多人游戏支持和竞技)
- 编写苹果游戏中心应用程序(翻译 1.1 GCD和块对象介绍)
- 编写苹果游戏中心应用程序(翻译 1.10 向排行榜提交得分)
- 编写苹果游戏中心应用程序(翻译 1.11 编程获取排行榜信息)
- 编写苹果游戏中心应用程序(翻译 1.15 编程获取成就信息)
- poj 2886 Who Gets the Most Candies?
- VS2008 打开VS2010解决方案及项目
- 最小编辑距离的理解
- hdu3851.Beat It!
- Java开发环境搭建
- 编写苹果游戏中心应用程序(翻译 1.5 在游戏中心验证本地玩家)
- LS代理中调用方法并且得到返回值
- Joomla! (DAY 9) - Joomsport (DAY 7): Create a Real View 'Home VS Away'
- 我对架构的理解-概念篇
- 二、Python:控制结构
- sed命令的备注
- 排序 2 选择排序
- Zendframework2-Zend_View-视图助手-区域助手(Partial Helper)
- Larbin小技巧:将字符变为小写,如果本身是小写字母,则保持不变。