ios 7 내 구 매, Game Center 인 앱 구 매 실현 & Game Center
원본 주소: 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
주석 은 이미 분명하게 썼 으 니, 더 이상 명확 하지 않 은 것 은 메 시 지 를 남 길 수 있다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
Pots of gold game: 누가 돈을 많이 받는지Pots of gold game: Two players A & B. 간단하게 말하면 많은 금화통이 한 줄로 늘어서서 두 사람이 번갈아 돈을 받는다.매번 실 끝에 있는 깡통만 가져가도 두 가지 선택이 있다.A부터 시작...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.