簡介
GameKit是 iOS 應用程式框架,提供了領先及更多功能。在本教程中,我們將解釋領先板上及更新分數步驟。
涉及的步驟
1. 在iTunes連接,確保您擁有一個獨特的應用程式ID和相應的配置檔捆綁ID和代碼簽名,在Xcode當我們創建應用程式更新。
2. 創建一個新的應用和更新應用程式的資訊。可以知道更多關於這個蘋果添加新的應用程式文檔。
3. 設置一個領先板上,在遊戲中心管理應用程式的頁面中添加一個排行榜,排行榜ID和分數類型。在這裏,我們給領先板上編號為 zaixianID。
4. 接下來的步驟是關係到我們的應用程式處理代碼和創建UI。
5. 創建一個單一的視圖應用程式並進入包識別字指定的識別字在iTunes連接。
6. 更新ViewController.xib,如下所示。
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:@"tutorialszaixian"]; } -(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 - iAd 整合
下一篇:
iOS - Storyboards(演示圖板演)