简体   繁体   English

IOS 7排行榜中的游戏中心

[英]Game Center in IOS 7 leaderboard

I have successfully added Game Center capabilities to my app. 我已成功将Game Center功能添加到我的应用程序中。 When the app is opened it successfully authenticates the user and shows the "Welcome back (UserName)" banner. 打开应用程序后,它会成功验证用户身份并显示“欢迎回来(UserName)”标语。

However, I am not sure of how to add a leaderboard to the game. 但是,我不确定如何在游戏中添加排行榜。 I was wondering if someone could help me A: Help me understand how to link the leaderboard i made in iTunes connect with the app and make highscore the value of the leaderboard. 我想知道是否有人可以帮助我答:帮助我了解如何将我在iTunes中制作的排行榜与应用程序链接,并使排行榜的价值高居榜首。 And B: Make the leaderboard show up in the app with all the rankings. B:让排行榜以所有排名显示在应用程序中。

All the code for gamecenter in my app so far is below. 到目前为止,我的应用程序中所有gamecenter的代码如下。

Interface File: 接口文件:

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


@interface GCHelper : NSObject {

BOOL gameCenterAvailable;
BOOL userAuthenticated;
}

@property (assign, readonly) BOOL gameCenterAvailable;

+ (GCHelper *)sharedInstance;
-(void)authenticateLocalUser;

@end

Implementation File: 实施文件:

#import "GCHelper.h"



@implementation GCHelper
@synthesize  gameCenterAvailable;

#pragma mark initialization

static GCHelper *sharedHelper = nil;
+ (GCHelper *) sharedInstance {
if (!sharedHelper) {
    sharedHelper = [[GCHelper alloc] init];
}
return sharedHelper;

}

- (BOOL)isGameCenterAvailable {
Class gcClass = (NSClassFromString(@"GKLocalPlayer"));

NSString *reqSysVer = @"4.1";
NSString *currSysVer = [[UIDevice currentDevice] systemVersion];
BOOL osVersionSupported = ([currSysVer compare:reqSysVer
                                       options:NSNumericSearch] != NSOrderedAscending);
return (gcClass && osVersionSupported);
}

- (id) init {
if ((self = [super init])) {
    gameCenterAvailable = [self isGameCenterAvailable];
    if(gameCenterAvailable) {
        NSNotificationCenter *nc =
        [NSNotificationCenter defaultCenter];
        [nc addObserver:self
               selector:@selector(authenticationChanged)
                   name:GKPlayerAuthenticationDidChangeNotificationName
                 object:nil];
    }
}
return self;
}

-(void)authenticationChanged {

if ([GKLocalPlayer localPlayer].isAuthenticated && !userAuthenticated) {
    NSLog(@"Authentication changed: player authenticated.");
    userAuthenticated = TRUE;
} else if (![GKLocalPlayer localPlayer].isAuthenticated && userAuthenticated) {
    NSLog(@"Authentication changed: player not authenticated");
    userAuthenticated = FALSE;
}
}

#pragma mark User Functions

-(void) authenticateLocalUser {

if(!gameCenterAvailable) return;

NSLog(@"Authentication local user...");
if ([GKLocalPlayer localPlayer].authenticated == NO) {
    [[GKLocalPlayer localPlayer] authenticateWithCompletionHandler:nil];
} else {
    NSLog(@"Already authenticated!");
}
}

@end

OKAY, so. 可以,然后呢。 The code is working now but when the code to access the leaderboard returns an error, I have no code to handle it and instead just makes the app go into a frozen state and makes it unable to function. 该代码现在可以正常工作,但是当访问排行榜的代码返回错误时,我没有任何代码可以处理它,而只是使应用程序进入冻结状态并使其无法运行。

Code being called to access leaderboard : 调用代码以访问排行榜:

- (void) presentLeaderboards
{
GKGameCenterViewController* gameCenterController = [[GKGameCenterViewController alloc]      init];
gameCenterController.viewState = GKGameCenterViewControllerStateLeaderboards;
gameCenterController.gameCenterDelegate = self;
[self presentViewController:gameCenterController animated:YES completion:nil];

}

To set up a leaderboard go to iTunes Connect > Manage Your Apps > Your App > Manage Game Center > Add Leaderboard > Single Leaderboard. 要设置排行榜,请转到iTunes Connect>管理您的应用>您的应用>管理游戏中心>添加排行榜>单个排行榜。

Give your leaderboard a name and all of the required organizational information needed. 给您的排行榜起一个名字,并提供所有需要的组织信息。

Add this method to your GCHelper.m : 将此方法添加到您的GCHelper.m

-(void) submitScore:(int64_t)score Leaderboard: (NSString*)leaderboard
{

    //1: Check if Game Center
    //   features are enabled
    if (!_gameCenterFeaturesEnabled) {
        return;
    }

    //2: Create a GKScore object
    GKScore* gkScore =
    [[GKScore alloc]
     initWithLeaderboardIdentifier:leaderboard];

    //3: Set the score value
    gkScore.value = score;

    //4: Send the score to Game Center
    [gkScore reportScoreWithCompletionHandler:
     ^(NSError* error) {

         [self setLastError:error];

         BOOL success = (error == nil);

         if ([_delegate
              respondsToSelector:
              @selector(onScoresSubmitted:)]) {

             [_delegate onScoresSubmitted:success];
         }
     }];


}

And add this to your GCHelper.h : 并将其添加到您的GCHelper.h

-(void) submitScore:(int64_t)score Leaderboard: (NSString*)leaderboard;

Now in the .m for your game add this method to whatever method you call when the game is over: 现在,在您的游戏的.m中,将此方法添加到游戏结束时调用的任何方法:

[[GCHelper sharedGameKitHelper] submitScore:highScore Leaderboard:LeaderboardName];

In this example highScore is the int_64 value of your score and LeaderboardName is an NSString equal to the Leaderboard Identifier you set up in iTunes Connect. 在此示例中, highScore是您的分数的int_64值,而LeaderboardName是一个NSString等于您在iTunes Connect中设置的Leaderboard标识符。 Also be sure to add Game Center capabilities to your application. 另外,请确保将Game Center功能添加到您的应用程序中。

After that you should be able to submit high scores! 之后,您应该能够提交高分!

ALSO ADD THIS TO GCHelper.m 也将此添加到GCHelper.m

-(void) setLastError:(NSError*)error {
    _lastError = [error copy];
    if (_lastError) {
        NSLog(@"GameKitHelper ERROR: %@", [[_lastError userInfo]
                                           description]);
    }
}

AND ALSO ADD THIS TO GCHelper.h 并且也将此添加到GCHelper.h

@property (nonatomic, assign)id<GCHelperProtocol> delegate;

Here is my GCHelper.h: 这是我的GCHelper.h:

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

//   Include the GameKit framework
#import <GameKit/GameKit.h>

//   Protocol to notify external
//   objects when Game Center events occur or
//   when Game Center async tasks are completed
@protocol GCHelperProtocol<NSObject>


-(void) onScoresSubmitted:(bool)success;


@end


@interface GCHelper : NSObject

@property (nonatomic, assign)id<GCHelperProtocol> delegate;

// This property holds the last known error
// that occured while using the Game Center API's
@property (nonatomic, readonly) NSError* lastError;

+ (id) sharedGameKitHelper;

// Player authentication, info
-(void) authenticateLocalPlayer;

//Scores
-(void) submitScore:(int64_t)score Leaderboard: (NSString*)leaderboard;




@end

And here my GCHelper.m: 这是我的GCHelper.m:

#import "GCHelper.h"

@interface GCHelper ()
<GKGameCenterControllerDelegate> {
    BOOL _gameCenterFeaturesEnabled;
}
@end

@implementation GCHelper

#pragma mark Singleton stuff

+(id) sharedGameKitHelper {
    static GCHelper *sharedGameKitHelper;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedGameKitHelper =
        [[GCHelper alloc] init];
    });
    return sharedGameKitHelper;
}

#pragma mark Player Authentication

-(void) authenticateLocalPlayer {

    GKLocalPlayer* localPlayer =
    [GKLocalPlayer localPlayer];

    localPlayer.authenticateHandler =
    ^(UIViewController *viewController,
      NSError *error) {

        [self setLastError:error];


        if (localPlayer.authenticated) {
            _gameCenterFeaturesEnabled = YES;
        } else if(viewController) {
            [self presentViewController:viewController];
        } else {
            _gameCenterFeaturesEnabled = NO;
        }
    };
}

#pragma mark Property setters

-(void) setLastError:(NSError*)error {
    _lastError = [error copy];
    if (_lastError) {
        NSLog(@"GameKitHelper ERROR: %@", [[_lastError userInfo]
                                           description]);
    }
}

#pragma mark UIViewController stuff

-(UIViewController*) getRootViewController {
    return [UIApplication
            sharedApplication].keyWindow.rootViewController;
}

-(void)presentViewController:(UIViewController*)vc {
    UIViewController* rootVC = [self getRootViewController];
    [rootVC presentViewController:vc animated:YES
                       completion:nil];
}


#pragma mark Scores

- (void) reportAchievementWithID:(NSString*) AchievementID {

    [GKAchievement loadAchievementsWithCompletionHandler:^(NSArray *achievements, NSError *error) {

        if(error) NSLog(@"error reporting ach");

        for (GKAchievement *ach in achievements) {
            if([ach.identifier isEqualToString:AchievementID]) { //already submitted
                return ;
            }
        }

        GKAchievement *achievementToSend = [[GKAchievement alloc] initWithIdentifier:AchievementID];
        achievementToSend.percentComplete = 100;
        achievementToSend.showsCompletionBanner = YES;
        [achievementToSend reportAchievementWithCompletionHandler:NULL];

    }];

}

-(void) submitScore:(int64_t)score Leaderboard: (NSString*)leaderboard
{

    //1: Check if Game Center
    //   features are enabled
    if (!_gameCenterFeaturesEnabled) {
        return;
    }

    //2: Create a GKScore object
    GKScore* gkScore =
    [[GKScore alloc]
     initWithLeaderboardIdentifier:leaderboard];

    //3: Set the score value
    gkScore.value = score;

    //4: Send the score to Game Center
    [gkScore reportScoreWithCompletionHandler:
     ^(NSError* error) {

         [self setLastError:error];

         BOOL success = (error == nil);

         if ([_delegate
              respondsToSelector:
              @selector(onScoresSubmitted:)]) {

             [_delegate onScoresSubmitted:success];
         }
     }];


}




-(void) gameCenterViewControllerDidFinish:(GKGameCenterViewController *)gameCenterViewController
{
    //nothing
}

@end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM