我正在尝试将所有IAP代码放在一个名为iapController的类中,并将其放在main.swift中。这是代码:
class iapController: UIViewController, SKPaymentTransactionObserver, SKProductsRequestDelegate {
var product:SKProduct!
class func offerUnlockLevels() {
SKPaymentQueue.defaultQueue().addTransactionObserver(self)
getProductInfo()
let payment:SKPayment = SKPayment (product: product)
SKPaymentQueue.defaultQueue().addPayment(payment)
}
func paymentQueue(queue: SKPaymentQueue!, updatedTransactions transactions: [AnyObject]!) {
for transaction:AnyObject in transactions {
if let trans:SKPaymentTransaction = transaction as? SKPaymentTransaction {
switch trans.transactionState {
case .Purchased:
println("inside purchased")
self.openAllLevels()
SKPaymentQueue.defaultQueue().finishTransaction(transaction as SKPaymentTransaction)
break
case .Failed:
println("inside failed")
SKPaymentQueue.defaultQueue().finishTransaction(transaction as SKPaymentTransaction)
break
case .Restored:
println("inside restored")
SKPaymentQueue.defaultQueue().restoreCompletedTransactions()
break
default:
break
}
}
}
}
func openAllLevels() {
println("inside openAllLevels()")
unlockAllLevelsButton.hidden = true
for var i=0; i<20; i++ {
levelCollectionButtons[i].setBackgroundImage(nil, forState: .Normal)
}
}
func productsRequest (request: SKProductsRequest!, didReceiveResponse response: SKProductsResponse!) {
let products = response.products
println(products)
if products.count != 0
{
product = products[0] as SKProduct
println(product.localizedTitle + "\n" + product.localizedDescription)
}
}
func getProductInfo() { //Checks if user can make IAP (has itunes account)
if (SKPaymentQueue.canMakePayments()) {
let productID:NSSet = NSSet(object: "Zero.UnlockAllLevels") //Hold our product ID
let request:SKProductsRequest = SKProductsRequest(productIdentifiers: productID)
request.delegate = self
request.start()
}
}
}
请注意,我将offerUnlockLevels()作为类级别函数,因为我想从其他视图控制器调用它。但是我收到错误:类型iapController.Type不符合协议&#39; SKPaymentTransactionObserver&#39;
如果我不使它成为类级函数,我无法从其他viewcontroller calsses中调用此函数。我做错了什么?
答案 0 :(得分:1)
如果我不使它成为类级函数,我无法从其他视图控制器calsses中调用此函数
当然可以。您可以从其他视图控制器调用视图控制器实例方法。您可以在任何类的实例上调用任何实例方法,只要它不是私有的。这就是 for 的实例方法。
例如,当你说
时self.navigationController!.pushViewController(someVC, animated:true)
...您正在调用视图控制器的实例方法 - 导航控制器是视图控制器,pushViewController:animated:
是实例方法,而不是类方法。
因此,取消class
指定并让offerUnlockLevels
成为实例方法,您就可以在iapController
类的任何实例上调用它。