您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 7 內購與 Game Center 實作:StoreKit 與 GameKit 整合

編輯:iOS 開發綜合

用 iOS 7 SDK 重新 build 時發現,舊的內購寫法有幾處已經被標記為棄用。趁著修正的機會把程式碼整理出來,同時把 Game Center 的部分一併包進同一個管理器。

PGStoreKitManager.h

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

@class ViewController;

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

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

+ (PGStoreKitManager *)getInstance;

// Game Center
- (void)authenticateLocalPlayer;                                     // 登入,需先設定 viewController
- (void)reportScore:(NSString *)identifier hiScore:(int64_t)score;   // 上傳積分
- (void)reportAchievementIdentifier:(NSString *)identifier
                   percentComplete:(float)percent;                    // 上傳成就
- (void)showLeaderboard:(NSString *)leaderboard;                     // 顯示排行榜
- (void)showAchievements;                                            // 顯示成就

// In-App Purchase
- (void)initStoreKit;                                                // 初始化內購
- (void)purchaseItem:(NSString *)identifier;                         // 購買

@end

單例與 Game Center

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

- (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;
    }
}

iOS 7 之後,登入流程改由 authenticateHandler 回傳一個需要呈現的 viewController,這是與舊版最大的差異——舊寫法直接呼叫 GKLocalPlayer 的舊 API,在新 SDK 下已不可用。

- (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) { /* 處理錯誤 */ }
    }];
}

- (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) { /* 處理錯誤 */ }
        }];
    }
}

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

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

內購流程

StoreKit 的購買是「查詢商品 → 加入佇列 → 等待交易狀態回呼」三段式,每個階段都要處理失敗路徑。

- (BOOL)canProcessPayments {
    return [SKPaymentQueue canMakePayments];
}

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

- (void)purchaseItem:(NSString *)identifier {
    if (![self canProcessPayments]) {
        NSLog(@"失敗:使用者關閉了 App 內購買權限");
        return;
    }
    SKProductsRequest *request = [[SKProductsRequest alloc]
        initWithProductIdentifiers:[NSSet setWithObject:identifier]];
    request.delegate = self;
    [request start];
}

- (void)productsRequest:(SKProductsRequest *)request
     didReceiveResponse:(SKProductsResponse *)response {
    NSArray *myProduct = response.products;
    if (myProduct.count == 0) {
        NSLog(@"失敗:無法取得商品資訊 %@", response.invalidProductIdentifiers);
        return;
    }
    SKPayment *payment = [SKPayment paymentWithProduct:myProduct[0]];
    [[SKPaymentQueue defaultQueue] addPayment:payment];
}

- (void)paymentQueue:(SKPaymentQueue *)queue
 updatedTransactions:(NSArray *)transactions {
    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 {
    [self recordTransaction:transaction];
    [self provideContent:transaction.payment.productIdentifier];
    [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
}

- (void)restoreTransaction:(SKPaymentTransaction *)transaction {
    [self recordTransaction:transaction];
    [self provideContent:transaction.originalTransaction.payment.productIdentifier];
    [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
}

- (void)failedTransaction:(SKPaymentTransaction *)transaction {
    NSLog(@"交易失敗,error code: %d", (int)transaction.error.code);
    if (transaction.error.code != SKErrorPaymentCancelled) {
        // 非使用者主動取消,可能需要提示
    }
    [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
}

註解已經寫得夠清楚,這裡補三個實務要點:一是 recordTransaction 與 provideContent 是兩個不可省略的環節,前者負責寫入交易記錄以對帳,後者才是真正把權益交給使用者;二是 observers 必須在 dealloc 中移除,否則會有殘留回呼;三是 SKErrorPaymentCancelled 代表使用者自己按了取消,不該跳出錯誤提示,這點常被忽略而影響體驗。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved