迅速:应用程式内购买字典中的价格

时间:2018-08-02 14:01:05

标签: ios swift

我的应用中有两次应用内购买。我想加载我的应用内购买价格。

我使用以下代码加载价格:

let productIds = Set(["purchase","purchase1"])
var products = [String:SKProduct]()
var price = [String: String]()

override func viewDidLoad() {
        super.viewDidLoad()

        if !(UserDefaults.standard.bool(forKey: "purchased")){
            if (SKPaymentQueue.canMakePayments()) {
                let productsRequest:SKProductsRequest = SKProductsRequest(productIdentifiers: productIds);
                productsRequest.delegate = self;
                productsRequest.start();
                print("Fetching Products");
            } else {
                print("Can't make purchases");
            }
        }

    }

func productsRequest (_ request: SKProductsRequest, didReceive response: SKProductsResponse) {

    for product in response.products {
        self.products[product.productIdentifier] = product

        price[product.productIdentifier] = localizedPriceForProduct(product)
        print(price)
    }
}

func localizedPriceForProduct(_ product:SKProduct) -> String {
    let priceFormatter = NumberFormatter()
    priceFormatter.formatterBehavior = NumberFormatter.Behavior.behavior10_4
    priceFormatter.numberStyle = NumberFormatter.Style.currency
    priceFormatter.locale = product.priceLocale
    return priceFormatter.string(from: product.price)!
}

但是在price中,我得到了这个结果

["purchase": "3,00 USD"]
["purchase": "3,00 USD", "purchase1": "1,00 USD"]

但是我需要得到这个:

["purchase": "3,00 USD", "purchase1": "1,00 USD"]

如何做到?

1 个答案:

答案 0 :(得分:0)

您正在for循环中进行打印,因此您的代码是正确的,只是打印在错误的行中。

尝试:

for product in response.products {
    self.products[product.productIdentifier] = product

    price[product.productIdentifier] = localizedPriceForProduct(product)
}
print(price)