用户可以选择购买“硬币”,然后可以用来购买不同类型的车辆在游戏过程中使用。Swift In App购买增加一个UserDefault值不会被刷新,直到应用程序重新加载
这是在应用程序内购买硬币的代码:
func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
for transaction in transactions {
switch (transaction.transactionState) {
case .purchased:
SKPaymentQueue.default().finishTransaction(transaction)
print("Purchased")
let oldCoin = UserDefaults.standard.integer(forKey: "COINSCORE")
let newCoin = oldCoin + 500
UserDefaults.standard.set(newCoin, forKey: "COINSCORE")
UserDefaults.standard.synchronize()
coinLabel.removeFromParent()
createCoinScore()
// apply purchased here and store info in userDefaults
case .failed:
SKPaymentQueue.default().finishTransaction(transaction)
print("Failed")
default:
break
}
}
}
此次购买可以正常使用,一旦购买完成的coinScore将增加。
问题是,当coinScore足以让玩家购买车辆时,它似乎不会注册增加的coinScore,直到通过重新加载应用程序或更改场景并返回加载视图之后才会注册增加的coinScore。
的coinScore被添加作为一个变量作为这样:
var coinScore = UserDefaults().integer(forKey: "COINSCORE")
这是允许玩家购买的车辆的代码:
if(atPoint(location) == greyship2){
if coinScore > 20 {
let oldValue = UserDefaults.standard.integer(forKey: "COINSCORE")
let newValue = oldValue - 20
UserDefaults.standard.set(newValue, forKey: "COINSCORE")
UserDefaults.standard.set(true, forKey: "ship2")
UserDefaults.standard.synchronize()
coinLabel.removeFromParent()
coinImage1.removeFromParent()
coinLabel1.removeFromParent()
createCoinScore()
greyship2.setScale(0)
greyship2.removeFromParent()
let ship2Texture = SKTexture(imageNamed: "ship2.png")
ship2 = SKSpriteNode(texture: ship2Texture)
ship2.position = CGPoint(x: self.frame.midX - 150, y: self.frame.midY)
ship2.setScale(1)
self.addChild(ship2)
break //finish the touchesbegan call
}
购买后,虽然在示出的coinScore值该视图会立即更新,用户不能再点击greyShip2来购买它,直到应用程序被刷新。