用戶可以選擇購買「硬幣」,然後可以用來購買不同類型的車輛在遊戲過程中使用。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來購買它,直到應用程序被刷新。