ios - iOS 7 排行榜中的游戏中心

标签 ios ios7 game-center

我已成功将 Game Center 功能添加到我的应用中。当应用程序打开时,它会成功验证用户身份并显示“欢迎回来(用户名)”横幅。

但是,我不确定如何将排行榜添加到游戏中。我想知道是否有人可以帮助我 A:帮助我了解如何将我在 iTunes 中制作的排行榜与应用程序连接起来,并使高分成为排行榜的值(value)。 B:让排行榜在应用中显示所有排名。

到目前为止,我应用中 gamecenter 的所有代码都在下面。

接口(interface)文件:

#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

执行文件:

#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

好的,所以。代码现在可以正常工作,但是当访问排行榜的代码返回错误时,我没有代码来处理它,而是让应用程序进入卡住状态并使其无法运行。

被调用以访问排行榜的代码:

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

}

最佳答案

要设置排行榜,请转至 iTunes Connect > 管理您的应用程序 > 您的应用程序 > 管理游戏中心 > 添加排行榜 > 单一排行榜。

为您的排行榜命名,并提供所有必需的组织信息。

将此方法添加到您的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];
         }
     }];


}

并将此添加到您的GCHelper.h:

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

现在在游戏的 .m 文件中,将此方法添加到游戏结束时调用的任何方法中:

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

在此示例中,highScore 是您得分的 int_64 值,LeaderboardName 是一个 NSString,等于您在 iTunes Connect 中设置的排行榜标识符。还要确保将 Game Center 功能添加到您的应用程序中。

之后你应该可以提交高分了!

还将此添加到 GCHelper.m

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

并将其添加到 GCHelper.h

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

这是我的 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

这是我的 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

关于ios - iOS 7 排行榜中的游戏中心,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24967767/

相关文章:

ios - 从程序集内部修补 Typhoon 程序集

iphone - 在运行 iOS7 的设备上测试 iOS 6 应用程序

ios - Swift 等效于 (__bridge NSArray*)

iphone - GameCenter GKMatchmakerViewController 自动匹配不起作用,expectedPlayerCount 始终为 1,解决方案?

iphone - 删除 GameCenter 排行榜 - iTunes Connect

iphone - 像表格 View 单元格一样绘制游戏中心

ios - 带有失真的 AvPlayer

ios - 如果用户取消 Facebook 登录,如何返回应用程序?

iphone - 应用 3d 动画查看

objective-c - 从 MCSession 断开单个对等体?