我正在尝试在Swift
应用程序中实现应用内购买,即使用产品IDproductID
进行消费性应用内购买。
研究
使用this answer,我了解了应用程序内购买的基本模式,并尝试对其进行调整。我不需要使用nsuserdefaults方法让应用程序记住是否进行了购买,因为我是用不同的解决方案来处理的。
代码
class ViewController: UICollectionViewController, SKProductsRequestDelegate, SKPaymentTransactionObserver {
viewDidLoad() {
//Unimportant stuff left out
product_id = "productID"
SKPaymentQueue.defaultQueue().addTransactionObserver(self)
}
@IBAction func thisISTheButtonToTriggerTheInAppPurchases(sender: AnyObject) {
if (SKPaymentQueue.canMakePayments()) {
var productID:NSSet = NSSet(object: self.product_id!);
var productsRequest:SKProductsRequest = SKProductsRequest(productIdentifiers: productID as! Set<String>);
productsRequest.delegate = self;
productsRequest.start();
print("Fetching Products");
}else{
print("can't make purchases");
}
}
func buyProduct(product: SKProduct){
print("Sending the Payment Request to Apple");
var payment = SKPayment(product: product)
SKPaymentQueue.defaultQueue().addPayment(payment);
}
func productsRequest (request: SKProductsRequest, didReceiveResponse response: SKProductsResponse) {
var count : Int = response.products.count
if (count>0) {
var validProducts = response.products
var validProduct: SKProduct = response.products[0] as SKProduct
if (validProduct.productIdentifier == self.product_id) {
print(validProduct.localizedTitle)
print(validProduct.localizedDescription)
print(validProduct.price)
buyProduct(validProduct);
} else {
print(validProduct.productIdentifier)
}
} else {
print("nothing")
}
}
func request(request: SKRequest!, didFailWithError error: NSError!) {
print("Error Fetching product information");
}
func paymentQueue(queue: SKPaymentQueue!, updatedTransactions transactions: [AnyObject]!) {
print("Received Payment Transaction Response from Apple");
for transaction:AnyObject in transactions {
if let trans:SKPaymentTransaction = transaction as? SKPaymentTransaction{
switch trans.transactionState {
case .Purchased:
print("Product Purchased");
SKPaymentQueue.defaultQueue().finishTransaction(transaction as! SKPaymentTransaction)
break;
case .Failed:
print("Purchased Failed");
SKPaymentQueue.defaultQueue().finishTransaction(transaction as! SKPaymentTransaction)
break;
case .Restored:
print("Already Purchased");
SKPaymentQueue.defaultQueue().restoreCompletedTransactions()
default:
break;
}
}
}
}
}
错误
类型“viewcontroller”不符合协议“skpaymenttransactionobserver”
我对这个错误进行了一些研究,像this这样的消息来源表明,这种错误是由于没有所需的函数造成的。
According to Apple,
paymentQueue:updatedTransactions:
是唯一需要的,但我似乎正在实现它。我的一个可能的理论是我没有正确地实现它-如果是真的,我该如何解决?预期行为
应用程序显示,如果用户输入良好,则使用id
productID
执行iap。谢谢你的帮助,如果你需要更多的信息请告诉我!
最佳答案
很简单。错误是关于skpaymenttransactionobserver的。它唯一的required method是:
func paymentQueue(queue: SKPaymentQueue,
updatedTransactions transactions: [SKPaymentTransaction])
您的方法的签名不匹配:
func paymentQueue(queue: SKPaymentQueue!,
updatedTransactions transactions: [AnyObject]!)
……所以这不是同一种方法,所以你不服从。