首先你應該回去檢討In App Purchase的documentation,蘋果提供的代碼 - 他們勾勒出這詳細瞭解它,並且瞭解他們正在做什麼是有用的。
你缺少的是SKPaymentTransactionObserver - 你有責任實現這個觀察者,你添加爲SKPaymentTransactionQueue的觀察者。 Apple建議您將應用程序啓動時的觀察者添加到默認隊列中,以便它能夠觀察在您的應用程序運行時發生的所有事務。
本質上,您需要編寫自己的實現SKPaymentTransactionObserver協議的類。此類所要做的就是觀察當iTunes商店處理付款時從支付隊列中獲取回調,並讓您捕獲成功和失敗事件。
下面是付款觀察骨架:
PaymentObserver.h
#import <StoreKit/StoreKit.h>
@interface PaymentObserver : NSObject <SKPaymentTransactionObserver> {
}
- (void) completeTransaction: (SKPaymentTransaction *)transaction;
- (void) restoreTransaction: (SKPaymentTransaction *)transaction;
- (void) failedTransaction: (SKPaymentTransaction *)transaction;
@end
PaymentObserver.m
#import "PaymentObserver.h"
@implementation PaymentObserver
- (void)paymentQueue:(SKPaymentQueue *)queue removedTransactions:(NSArray *)transactions
{
// handle payment cancellation
}
- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions
{
// handle the payment transaction actions for each state
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];
default:
break;
}
}
}
- (void) completeTransaction: (SKPaymentTransaction *)transaction;
{
// Record the transaction
//...
// Do whatever you need to do to provide the service/subscription purchased
//...
// Remove the transaction from the payment queue.
[[SKPaymentQueue defaultQueue] finishTransaction: transaction];
}
- (void) restoreTransaction: (SKPaymentTransaction *)transaction
{
// Record the transaction
//...
// Do whatever you need to do to provide the service/subscription purchased
//...
[[SKPaymentQueue defaultQueue] finishTransaction: transaction];
}
- (void) failedTransaction: (SKPaymentTransaction *)transaction
{
if (transaction.error.code != SKErrorPaymentCancelled)
{
// Optionally, display an error here.
}
[[SKPaymentQueue defaultQueue] finishTransaction: transaction];
}
@end
一旦實現了PaymentObserver您需要關閉添加實例它作爲交易觀察者的默認支付隊列。
// Done at app launch...
PaymentObserver *paymentObserver = [[PaymentObserver alloc] init];
[[SKPaymentQueue defaultQueue] addTransactionObserver:paymentObserver];
嘿,這個答案今天保存了我的培根。確定它在蘋果文檔中,但我試圖修復另一個開發人員編寫的代碼中的錯誤,並查看了這一點,我能夠看到他錯過了什麼。謝謝! –