iOS - GameKit

簡介

GameKit是 iOS 應用程序框架,提供了領先及更多功能。在本教程中,我們將解釋領先板上及更新分數步驟。

涉及的步驟

1. 在iTunes連接,確保您擁有一個獨特的應用程序ID和相應的配置文件捆綁ID和代碼簽名,在Xcode當我們創建應用程序更新。

2. 創建一個新的應用和更新應用程序的信息。可以知道更多關於這個蘋果添加新的應用程序文檔。

3. 設置一個領先板上,在遊戲中心管理應用程序的頁面中添加一個排行榜,排行榜ID和分數類型。在這裏,我們給領先板上編號爲 yiibaiID。

4. 接下來的步驟是關係到我們的應用程序處理代碼和創建UI。

5. 創建一個單一的視圖應用程序並進入包標識符指定的標識符在iTunes連接。

6. 更新ViewController.xib,如下所示。

iOS

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:@"tutorialsYiibai"]; } -(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

當我們單擊「顯示領先者板上,我們會得到一個類似於下面的屏幕。

iOS

當我們點擊更新分數,比分將被更新到我們領先板上,我們會得到一個警告,如下圖所示。

iOS