[objective-c]GameCenter

なんとなく作ったGameCenterManager

#import "GameCenterManager.h"

GameCenterManager*gcm;
gcm=[[GameCenterManager alloc]initWithDelegate:self func:@selector(whenGameCenterEvent:)];
[gcm authenticateLocalPlayer];

-(void)whenGameCenterEvent:(NSNumber*)nm{
    NSLog(@"whenGameCenterEvent %d",[nm intValue]);
}

GameCenterManager.h

#import 
#import 

@interface GameCenterManager : NSObject{
    BOOL login;
@private
    
    id del;
    SEL func;
    /*
     1:認証成功
     2:認証失敗
     3:スコア報告成功
     4:スコア報告失敗
     5:リーダーボード表示失敗
    */
}
@property(nonatomic,assign)BOOL login;
-(id)initWithDelegate:(id)_d func:(SEL)_f;
- (void) authenticateLocalPlayer;
- (void) reportScore: (int64_t) score forCategory: (NSString*) category;
-(void)reportScore:(int64_t)score;
- (void) showLeaderboard;

@end

GameCenterManager.m


#import "GameCenterManager.h"

@implementation GameCenterManager

static NSString*leaderBoardID=@"hoge";

@synthesize login;

-(id)init{
    self=[super init];
    if (self) {
        login=NO;
    }
    return self;
}
-(id)initWithDelegate:(id)_d func:(SEL)_f{
    self=[self init];
    del=_d;
    func=_f;
    return self;
}
-(void)exeEvent:(int)t{
    NSNumber*n=[NSNumber numberWithInt:t];
    if (del && func && [del respondsToSelector:func]) {
        [del performSelector:func withObject:n];
    }
}



-(void)dealloc{
    del=nil;
    func=nil;
    [super dealloc];
}


//step1:プレーヤー認証 最速で実行
- (void) authenticateLocalPlayer
{
    GKLocalPlayer *localPlayer = [GKLocalPlayer localPlayer];
    [localPlayer authenticateWithCompletionHandler:^(NSError *error) {
        if (localPlayer.isAuthenticated){
            // 認証済みプレーヤーの追加タスクを実行する
            login=YES;
            [self exeEvent:1];
        }else{
            [self exeEvent:2];
        }
        }];
}


//step2:スコア報告
//category:リーダーボードのID
- (void) reportScore: (int64_t) score forCategory: (NSString*) category
{
    if (!login) {
        [self exeEvent:4];
        return;
    }
    GKScore *scoreReporter = [[[GKScore alloc] initWithCategory:category]autorelease];
    scoreReporter.value = score;
    [scoreReporter reportScoreWithCompletionHandler:^(NSError *error) {
        if (error != nil){
            // 報告エラーの処理
            [self exeEvent:4];
        }else{
            [self exeEvent:3];
        }
        }];
}
-(void)reportScore:(int64_t)score{
    [self reportScore:score forCategory:leaderBoardID];
}

- (void)leaderboardViewControllerDidFinish:(GKLeaderboardViewController*)viewController
{
    [viewController dismissModalViewControllerAnimated:YES];
}

//リーダーボード表示
- (void) showLeaderboard
{
    GKLeaderboardViewController *leaderboardController =[[[GKLeaderboardViewController alloc] init]autorelease];
    if (leaderboardController != nil)
    {
        leaderboardController.leaderboardDelegate=self;
        [del presentModalViewController: leaderboardController animated: YES];
    }else{
        [self exeEvent:5];
    }
}

@end