ios7內購、Game Center 實現 in-App Purchases & Game Ce

來源:互聯網
上載者:User

 

 

昨天使用ios7SDK build的時候,發現了幾個warning,原來以前寫的內購方法,有些在ios7下棄用了。今天改了下,順便代碼也發上。

PGStoreKitManager.h

 

 

////  PGStoreKitManager.h//  OCPhysicGame////  Created by LiuYanghui on 14-1-26.//  Copyright (c) 2014年 LiuYanghui. All rights reserved.//#import #import #import @class ViewController;@interface PGStoreKitManager : NSObject{    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

注釋已經寫的很清楚了,再有不清楚的可以留言。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.