iOS - GameKit

Gamekit是一个为iOS应用程序提供排行榜,成就和更多功能的框架.在本教程中,我们将解释添加排行榜和更新分数所涉及的步骤.

涉及的步骤

步骤1 : 在iTunes连接中,确保您拥有唯一的应用ID 以及我们使用捆绑包ID 创建应用程序更新以及使用相应的配置文件在Xcode中进行代码签名.

第2步 : 创建新应用程序并更新应用程序信息.您可以在Apple-add新应用文档中了解更多相关信息.

第3步 : 在应用程序页面的管理游戏中心中设置排行榜,在该页面中添加单个排行榜并提供排行榜ID 和得分类型.在这里,我们将排行榜ID作为tutorialsPoint.

第4步 : 接下来的步骤与处理代码和为我们的应用程序创建UI有关.

第5步 : 创建单一视图应用程序并输入包标识符 iTunes连接中指定的标识符.

第6步 : 更新ViewController.xib,如下所示 :

iOS Tutorial

第7步 : 选择项目文件,然后选择目标,然后添加 GameKit.framework .

步骤8 : 号;为我们添加的按钮创建 IBActions .

第9步 : 更新 ViewController.h 文件,如下所示 :

#import <UIKit/UIKit.h>
#import <GameKit/GameKit.h>

@interface ViewController : UIViewController
<GKLeaderboardViewControllerDelegate>

-(IBAction)updateScore:(id)sender;
-(IBAction)showLeaderBoard:(id)sender;

@end

第10步 : 更新 ViewController.m 如下 :

#import "ViewController.h"

@interface ViewController ()
@end

@implementation ViewController

- (void)viewDidLoad {
   [super viewDidLoad];
   if([GKLocalPlayer localPlayer].authenticated == NO) {
      [[GKLocalPlayer localPlayer] 
      authenticateWithCompletionHandler:^(NSError *error) {
         NSLog(@"Error%@",error);
      }];
   }    
}

- (void)didReceiveMemoryWarning {
   [super didReceiveMemoryWarning];
   // Dispose of any resources that can be recreated.
}

- (void) updateScore: (int64_t) score 
   forLeaderboardID: (NSString*) category {
   GKScore *scoreObj = [[GKScore alloc]
   initWithCategory:category];
   scoreObj.value = score;
   scoreObj.context = 0;
   
   [scoreObj reportScoreWithCompletionHandler:^(NSError *error) {
      // Completion code can be added here
      UIAlertView *alert = [[UIAlertView alloc]
      initWithTitle:nil message:@"Score Updated Succesfully" 
      delegate:self cancelButtonTitle:@"Ok" otherButtonTitles: nil];
      [alert show];
   }];
}

-(IBAction)updateScore:(id)sender {
   [self updateScore:200 forLeaderboardID:@"tutorialsPoint"];
}

-(IBAction)showLeaderBoard:(id)sender {
   GKLeaderboardViewController *leaderboardViewController =
   [[GKLeaderboardViewController alloc] init];
   leaderboardViewController.leaderboardDelegate = self;
   [self presentModalViewController:
   leaderboardViewController animated:YES];
}

#pragma mark - Gamekit delegates
- (void)leaderboardViewControllerDidFinish:
(GKLeaderboardViewController *)viewController {
   [self dismissModalViewControllerAnimated:YES];
}
@end

输出

当我们运行应用程序时,我们会得到以下输出 :

iOS Tutorial

当我们点击"显示排行榜",我们会得到一个类似于以下的屏幕;

iOS Tutorial

当我们点击"更新分数"时,分数将更新到我们的排行榜,我们将收到如下所示的警告和减号;

iOS教程