猴子原创,欢迎转载。转载请注明: 转载自Cocos2D开发网–Cocos2Dev.com,谢谢!

原文地址: http://www.cocos2dev.com/?p=514

昨天使用ios7SDK build的时候,发现了几个warning,原来以前写的内购方法,有些在ios7下弃用了。今天改了下,顺便代码也发上。

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

注释已经写的很清楚了,再有不清楚的可以留言。

ios7内购、Game Center 实现 in-App Purchases & Game Center的更多相关文章

  1. 苹果开发——App内购以及验证store的收据(一)

    原地址:http://zengwu3915.blog.163.com/blog/static/27834897201375105236580?suggestedreading 发了几天时间在网上折腾了 ...

  2. iOS内购图文流程(2017)

    什么是内购? 只要在iPhone App上购买的不是实物产品(也就是虚拟产品如qq币.虎牙币.电子书......) 都需要走内购流程,苹果这里面抽走三成.   使用内购需要走的流程. 1,填写协议,税 ...

  3. 萝卜保卫战3内购破解+Toast窗口增加(Love版)

    涉及到一些不同的破解的方法,以及不同的破解思路,还有一些重要权限的删除等. 作者:HAI_ 这次目标是经常玩的萝卜保卫战,不知不觉,已经更新到3了.详细分析请参考https://bbs.ichunqi ...

  4. iOS- 给App添加内购& 验证购买iOS7新特性

    1.内购——应用内购买 我所说的内购——也可以说是应用内购买 大家都知道通过苹果应用程序商店有三种主要赚钱的方式: 1.直接收费(与国内大部分用户的消费习惯相悖,如果要收费,直接收高的,别收6块钱) ...

  5. [IPA]IOS In App Purchase(内购)验证

    参考我之前的笔记 苹果内购笔记,在客户端向苹果购买成功之后,我们需要进行二次验证. 二次验证 IOS在沙箱环境下购买成功之后,向苹果进行二次验证,确认用户是否购买成功. 当应用向Apple服务器请求购 ...

  6. 苹果开发——App内购以及验证store的收据(二)

    原地址:http://zengwu3915.blog.163.com/blog/static/2783489720137605156966?suggestedreading 三. 客户端使用Store ...

  7. iOS APP内购

    看到网上文章一大把,看了这个觉得挺不错的,谢谢 iOS大全 公众平台; 原文:http://mp.weixin.qq.com/s?__biz=MzAxMzE2Mjc2Ng==&mid=2652 ...

  8. [Xcode 实际操作]九、实用进阶-(29)为App添加IAP(支付方式)内购项目

    目录:[Swift]Xcode实际操作 首先请阅读:[Xcode10 实际操作]九.实用进阶-(28)在iTunes Connect(苹果商店的管理后台)中创建一个新的新的APP 本文将演示如何给刚刚 ...

  9. 苹果APP内购客户付款成功,没收到相应虚拟产品的解决办法

    一.引导用户走申请苹果的退款 1.告知用户新版本可以使用支付宝.微信支付,更划算 2.苹果可申请90天以内的退款,一般情况申请后48小时内就有反馈. 参考链接 https://jingyan.baid ...

随机推荐

  1. NOIP2014-5-24模拟赛

    Problem 1 护花(flower.cpp/c/pas) [题目描述] 约翰留下他的N(N<=100000)只奶牛上山采木.他离开的时候,她们像往常一样悠闲地在草场里吃草.可是,当他回来的时 ...

  2. Codeforces Round#402(Div.1)掉分记+题解

    哎,今天第一次打div1 感觉头脑很不清醒... 看到第一题就蒙了,想了好久,怎么乱dp,倒过来插之类的...突然发现不就是一道sb二分吗.....sb二分看了二十分钟........ 然后第二题看了 ...

  3. python设计模式浅析

    今天简单聊聊python的设计模式,GOF设计模式(c++)和Head first design pattern(Java)是两本设计模式的经典,基本可以照搬在python上面,但是你会发现pytho ...

  4. 如何理解主函数main中变量(int argc,char *argv[])的含义

    每一个C语言的初学者,都会注意到主函数main()里的两个参数,但是初学者一般不会去关注这两个参数的具体作用,下面我们就来介绍这两个参数的具体作用. main()函数是控制台程序的入口,int mai ...

  5. swiper实现臭美app滑动效果

    一.臭美app效果: 我的需求是这样,上面正常滑动,点击下面的小卡牌,上面的滑动区也随之切换到当前的点击态. 二.实现: css: 主要设置可见区域的几张卡牌的位置,注意的几个位置是,中间的激活态和左 ...

  6. 使用CSS让多出来的字变为省略号

    <style> .text1 { width:200px; overflow:hidden; text-overflow:ellipsis; -o-text-overflow:ellips ...

  7. Web压力测试和手机App测试

    总纲:认识测试关系和目标http://blog.csdn.net/superxgl/article/details/27189631 一.web测试和App服务端测试 软件安装 建议安装loadrun ...

  8. vue-cli搭建项目的目录结构及说明

    vue-cli基于webpack搭建项目的目录结构 build文件夹 ├── build              // 项目构建的(webpack)相关代码    │ ├── build.js   ...

  9. Angular5 路由传参的3种方法

    一共3种方法. 1.问号后面带的参数,获取参数的方式:ActivatedRoute.queryParams[id] 例如:/product?id=1&name=iphone还可以是: [rou ...

  10. Gradle 1.12用户指南翻译——第五十三章. 签名插件

    其他章节的翻译请参见:http://blog.csdn.net/column/details/gradle-translation.html翻译项目请关注Github上的地址:https://gith ...