我使用此代码创建我的应用内购买:
import UIKit
import StoreKit
class ViewController: UIViewController, SKProductsRequestDelegate, SKPaymentTransactionObserver, SKStoreProductViewControllerDelegate {
var product_id: String?
@IBOutlet weak var buyButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
product_id = "product_id"
SKPaymentQueue.default().add(self)
}
@IBAction func unlockAction(sender: AnyObject) {
print("About to fetch the product...")
// Can make payments
if (SKPaymentQueue.canMakePayments())
{
let productID:NSSet = NSSet(object: self.product_id!);
let 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");
let payment = SKPayment(product: product)
SKPaymentQueue.default().add(payment);
}
func productsRequest (_ request: SKProductsRequest, didReceive response: SKProductsResponse) {
let count : Int = response.products.count
if (count>0) {
let validProduct: SKProduct = response.products[0] as SKProduct
if (validProduct.productIdentifier == self.product_id) {
buyProduct(product: validProduct);
} else {
print(validProduct.productIdentifier)
}
} else {
print("nothing")
}
}
但是,如果我点击按钮(unlockAction)两次或点击一次,移动到不同的控制器,返回并再次点击我的应用程序在此行崩溃:
SKPaymentQueue.default().add(payment);
错误(lldb)
如何解决?
答案 0 :(得分:1)
您必须在结算控制器中使用viewWillDissappear()
功能。试试那个。
override func viewWillDisappear(_ animated: Bool) {
SKPaymentQueue.default().remove(self)
}
我也遇到了这个问题,这已经解决了我的问题。
错误是代码中的
SKPaymentQueue.default().add(payment)
行。所以尝试这个解决方案,成为可靠的高效程序员。 快乐编码