ios 7 내 구 매, Game Center 인 앱 구 매 실현 & Game Center

원숭이 오리지널, 전재 환영.전재 설명: Cocos2D 개발 망 에서 옮 겨 싣 기 – Cocos2dev. com, 감사합니다!
원본 주소: http://www.cocos2dev.com/?p=514
어제 ios7SDK build 를 사용 할 때 몇 개의 warning 을 발 견 했 습 니 다. 원래 예전 에 쓴 내 구 매 방법 중 일 부 는 ios 7 에서 버 렸 습 니 다.오늘 고 친 김 에 코드 도 보 냈 습 니 다.
PGStoreKitManager.h
//
//  PGStoreKitManager.h
//  OCPhysicGame
//
//  Created by LiuYanghui on 14-1-26.
//  Copyright (c) 2014  LiuYanghui. All rights reserved.
//

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

@class ViewController;
@interface PGStoreKitManager : NSObject<GKGameCenterControllerDelegate, SKPaymentTransactionObserver, SKProductsRequestDelegate>
{
    UIAlertView *_loadingAlert;
    BOOL _enableGameCenter;
}

@property (nonatomic, readwrite, strong) ViewController* viewController;
+ (PGStoreKitManager *)getInstance;

// game center ----------------------------------------
/**
   gamecenter,    setViewController
 */
- (void)authenticateLocalPlayer;

/**
     
 */
- (void)reportScore : (NSString*)identifier hiScore:(int64_t)score;

/**
     
 */
- (void)reportAchievementIdentifier : (NSString*)identifier percentComplete:(float)percent;

/**
      
 */
- (void)showLeaderboard : (NSString*)leaderboard;

/**
     
 */
- (void)showAchievements;


// iap  ----------------------------------------
/**
       
 */
- (void)initStoreKit;

/**
     
 */
- (void)purchaseItem: (NSString*)identifier;


@end

PGStoreKitManager.m
//
//  PGStoreKitManager.m
//  OCPhysicGame
//
//  Created by LiuYanghui on 14-1-26.
//  Copyright (c) 2014  LiuYanghui. All rights reserved.
//

#import "PGStoreKitManager.h"
#import "ViewController.h"

@implementation PGStoreKitManager

+ (PGStoreKitManager *)getInstance
{
    static PGStoreKitManager *mgr = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        mgr = [[self alloc] init];
    });
    return mgr;
}

- (id)init
{
    self = [super init];
    if (self) {
        [self initData];
        return self;
    }
    return nil;
}

- (void)initData
{
    _enableGameCenter = NO;
    _viewController = nil;
}

- (void)showMessage:(NSString *)title Message:(NSString *)msg
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title message:msg delegate:self cancelButtonTitle:@"  " otherButtonTitles:nil, nil];
    [alert show];
}

- (void)showLoadingView:(NSString *)title
{
    _loadingAlert= [[UIAlertView alloc] initWithTitle:title message:@"" delegate:self cancelButtonTitle:nil otherButtonTitles:nil, nil];
    [_loadingAlert show];
}

- (void)removeLoadingView
{
    [_loadingAlert dismissWithClickedButtonIndex:0 animated:YES];
}

#pragma mark - GameCenter
- (void)authenticateLocalPlayer
{
    GKLocalPlayer* localPlayer = [GKLocalPlayer localPlayer];
    if ([localPlayer isAuthenticated] == NO) {
        localPlayer.authenticateHandler = ^(UIViewController *viewController,
          NSError *error) {
            if (error) {
                _enableGameCenter = NO;
            }else{
                _enableGameCenter = YES;
                if(viewController) {
                    [_viewController presentViewController:viewController animated:YES completion:nil];
                }
            }
        };
    }else{
        _enableGameCenter = YES;
    }
}

/**
     
 */
- (void)reportScore : (NSString*)identifier hiScore:(int64_t)score;
{
    if (score < 0 || !_enableGameCenter)
		return;
	GKScore *scoreBoard = [[GKScore alloc] initWithLeaderboardIdentifier:identifier];
    scoreBoard.value = score;
    [GKScore reportScores:@[scoreBoard] withCompletionHandler:^(NSError *error) {
        if (error) {
            // handle error
        }
    }];
}

/**
     
 */
- (void)reportAchievementIdentifier : (NSString*)identifier percentComplete:(float)percent
{
    if (percent < 0 || !_enableGameCenter)
		return;
	
    GKAchievement *achievement = [[GKAchievement alloc] initWithIdentifier: identifier];
    if (achievement){
		achievement.percentComplete = percent;
        [GKAchievement reportAchievements:@[achievement] withCompletionHandler:^(NSError *error) {
            if (error) {
                // handle error
            }
        }];
    }
}

/**
      
 */
- (void)showLeaderboard : (NSString*)leaderboard
{
    if (!_enableGameCenter)
		return;
    GKGameCenterViewController *gameCenterViewController = [[GKGameCenterViewController alloc] init];
    gameCenterViewController.viewState = GKGameCenterViewControllerStateLeaderboards;
    gameCenterViewController.gameCenterDelegate = self;
    [_viewController presentViewController:gameCenterViewController animated:YES completion:nil];
}

/**
     
 */
- (void)showAchievements
{
    if (!_enableGameCenter)
		return;

    GKGameCenterViewController *gameCenterViewController = [[GKGameCenterViewController alloc] init];
    gameCenterViewController.viewState = GKGameCenterViewControllerStateAchievements;
    gameCenterViewController.gameCenterDelegate = self;
    [_viewController presentViewController:gameCenterViewController animated:YES completion:nil];
}

#pragma mark gameCenterViewController Close  
- (void)gameCenterViewControllerDidFinish:(GKGameCenterViewController *)gameCenterViewController
{
    [_viewController dismissViewControllerAnimated:YES completion:nil];
}





//---------------------------------------------------------
#pragma mark - IAP
- (BOOL)canProcessPayments
{
    if ([SKPaymentQueue canMakePayments]) {
        return YES;
    } else {
        return NO;
    }
}


/**
       
 */
- (void)initStoreKit
{
    [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
}

/**
     
 */
- (void)purchaseItem: (NSString *)identifier
{
    [self showLoadingView:@"Access Store..."];
    
    if (![self canProcessPayments]) {
        NSLog(@"1.  -->SKPaymentQueue canMakePayments NO");
        [self removeLoadingView];
        return;
    }
    NSLog(@"1.  -->      ...%@", identifier);
    
    //            
    SKProductsRequest *request= [[SKProductsRequest alloc]
                                 initWithProductIdentifiers: [NSSet setWithObject: identifier]];
    request.delegate = self;
    [request start];
}

// SKProductsRequest    
- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response
{
    NSArray *myProduct = response.products;

    if (myProduct.count == 0) {
        NSLog(@"2.  -->        ,    。invalidProductIdentifiers = %@",response.invalidProductIdentifiers);
        [self removeLoadingView];
        return;
    }
    NSLog(@"2.  -->        ,    ...");
    SKPayment * payment = [SKPayment paymentWithProduct:myProduct[0]];
    [[SKPaymentQueue defaultQueue] addPayment:payment];
}

// SKPayment    
- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions
{
    NSLog(@"3.  -->        ,    ...");
    for (SKPaymentTransaction *transaction in transactions){
        switch (transaction.transactionState){
            case SKPaymentTransactionStatePurchased:
                [self completeTransaction:transaction];
                break;
                
            case SKPaymentTransactionStateFailed:
                [self failedTransaction:transaction];
                break;
                
            case SKPaymentTransactionStateRestored:
                [self restoreTransaction:transaction];
                break;
                
            default:
                break;
        }
    }
}

//     
- (void) completeTransaction: (SKPaymentTransaction*)transaction
{
    NSLog(@"4.  -->     SKPaymentTransactionStatePurchased");
    [self removeLoadingView];
	//                   
    [self recordTransaction: transaction];
    [self provideContent: transaction.payment.productIdentifier];
	
    //    transaction from the payment queue.
    [[SKPaymentQueue defaultQueue] finishTransaction: transaction];
}

//     
- (void) restoreTransaction: (SKPaymentTransaction*)transaction
{
    NSLog(@"4.  -->     SKPaymentTransactionStateRestored");
    [self recordTransaction: transaction];
    [self provideContent: transaction.originalTransaction.payment.productIdentifier];
    [[SKPaymentQueue defaultQueue] finishTransaction: transaction];
}

//     
- (void) failedTransaction: (SKPaymentTransaction*)transaction
{
    [self removeLoadingView];
    NSLog(@"4.  -->     SKPaymentTransactionStateRestored error.code:%d",(int)transaction.error.code);
    [[SKPaymentQueue defaultQueue] finishTransaction: transaction];
}

//     
- (void) recordTransaction: (SKPaymentTransaction*)transacation
{
    NSLog(@"4.  -->    ,          ");
}

//     
- (void) provideContent: (NSString*)identifier
{
    NSLog(@"4.  -->    ,      identifier = %@", identifier);
    
    [self removeLoadingView];
    [self showMessage:@"Success" Message:@"You have successfully purchased."];
}

@end

주석 은 이미 분명하게 썼 으 니, 더 이상 명확 하지 않 은 것 은 메 시 지 를 남 길 수 있다.

좋은 웹페이지 즐겨찾기