我正在制作iPhone游戏。我正在关注游戏资金结算的Swift In-App Billing教程。我完成了所有Swift编码和构建,然后点击屏幕上的按钮,但弹出窗口没有弹出。请告诉我我的代码有什么问题。
import UIKit
import AVFoundation
import StoreKit
class ViewController: UIViewController,UIScrollViewDelegate,SKProductsRequestDelegate, SKPaymentTransactionObserver {
@IBOutlet var outAddCoins: UIButton!
@IBAction func btnAddCoins(_ sender: Any) {
for product in list {
let prodID = product.productIdentifier
if(prodID == "Add500000Credit") {
p = product
buyProduct()
}
}
}
func buyProduct() {
print("buy " + p.productIdentifier)
let pay = SKPayment(product: p)
SKPaymentQueue.default().add(self)
SKPaymentQueue.default().add(pay as SKPayment)
}
func addCoins() {
playerMoney += 500000
MoneyLabel.text = "\(playerMoney)"
}
var list = [SKProduct]()
var p = SKProduct()
func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) {
print("product request")
let myProduct = response.products
for product in myProduct {
print("product added")
print(product.productIdentifier)
print(product.localizedTitle)
print(product.localizedDescription)
print(product.price)
list.append(product)
}
outAddCoins.isEnabled = true
}
func paymentQueueRestoreCompletedTransactionsFinished(_ queue: SKPaymentQueue) {
print("transactions restored")
for transaction in queue.transactions {
let t: SKPaymentTransaction = transaction
let prodID = t.payment.productIdentifier as String
switch prodID {
case "Add500000Credit":
print("add coins to account")
addCoins()
default:
print("IAP not found")
}
}
}
func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
print("add payment")
for transaction: AnyObject in transactions {
let trans = transaction as! SKPaymentTransaction
print(trans.error)
switch trans.transactionState {
case .purchased:
print("buy ok, unlock IAP HERE")
print(p.productIdentifier)
let prodID = p.productIdentifier
switch prodID {
case "Add500000Credit":
print("add coins to account")
addCoins()
default:
print("IAP not found")
}
queue.finishTransaction(trans)
case .failed:
print("buy error")
queue.finishTransaction(trans)
break
default:
print("Default")
break
}
}
}
这是viewdidload部分
override func viewDidLoad() {
super.viewDidLoad()
outAddCoins.isEnabled = false
if(SKPaymentQueue.canMakePayments()) {
print("IAP is enabled, loading")
let productID: NSSet = NSSet(objects: "Add500000Credit")
let request: SKProductsRequest = SKProductsRequest(productIdentifiers: productID as! Set<String>)
request.delegate = self
request.start()
} else {
print("please enable IAPS")
}
}
我使用的是最新版本的Xcode。我已完成iTunes Connect中应用内购买的所有配置,但构建后不会弹出购买弹出窗口。我很感激你的帮助。
buy Add500000Credit
add payment
nil
Default
add payment
Optional(Error Domain=SKErrorDomain Code=0 "can not connect to the iTunes Store" UserInfo={NSLocalizedDescription=can not connect to the iTunes Store})
buy error
答案 0 :(得分:5)
测试应用内购买很棘手:
确保您已创建沙盒帐户以进行测试。
在设备上测试,而不是在模拟器中测试。你不能在模拟器中测试。
请记得在测试之前在设备上注销iCloud。否则,您将无法使用沙箱帐户。