iOS GameKit
簡介
GameKit是iOS SDK中一個常用的框架。其核心功能有3個:
- 互動遊戲平臺Game Center,
- P2P裝置通訊功能
- In-Game Voice。
例項步驟
1.在連結 iTunes 時請確保擁有一個唯一的 App ID( unique App ID),App ID在我們應用程式更新 bundle ID時及在Xcode程式碼簽名與相應的配置檔案需要使用到。
2.建立新的應用程式和更新應用程式資訊。在新增新的應用程式文件可以瞭解更多有關資訊。
3.開啟你申請的application,點選Manage Game Center選項。進入後點擊Enable Game Center使你的Game Center生效。接下來設定自己的Leaderboard和Achievements。
4.下一步涉及處理程式碼,併為我們的應用程式建立使用者介面。
5.建立一個single view application,並輸入 bundle identifier 。
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 = https://www.itread01.com/ios/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:@"itread01"]; } -(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
輸出
執行該應用程式,輸出結果如下
當我們單擊顯示排行榜時,螢幕顯示如下:
當我們點選更新分數,比分將被更新到我們排行榜上,我們會得到一個資訊,如下圖所示