Ben Dodson

Freelance iOS, macOS, Apple Watch, and Apple TV Developer

SKProduct localized price in Swift

I’m currently working on a Swift project which uses In App Purchasing (IAP). One of the many pitfalls of IAP is displaying the cost of a product in the correct format; all too often developers use the default US formatting leading to apps showing prices of $0.99 in the UK. Gross!

You may think you can use the locale of the device to format the number and you’d be correct apart from the user may be using an App Store in a different locale to that of their device (i.e. a UK account but they have their device sent to French if that is their primary language). The SKProduct object that iTunes returns has a locale attached so it is fairly simple to format the price with that in order to get the localized version:

import StoreKit

extension SKProduct {
    
    func localizedPrice() -> String {
        let formatter = NSNumberFormatter()
        formatter.numberStyle = .CurrencyStyle
        formatter.locale = self.priceLocale
        return formatter.stringFromNumber(self.price)!
    }
    
}

The above is a simple Swift extension (also available on GitHub) which, if it is in your project, will automatically be available on any SKProduct object (similar to using Categories in Objective-C). If we assume we have an SKProduct called product, we can now run:

NSLog("The price of this product is \(product.localizedPrice())")
// Example output: The price of this product is £0.99

It’s amazing how many apps either don’t display the price of an IAP in advance or display it in the wrong locale. Don’t let your app be one of them.

Update, July 2018: I’ve updated this script so that it is now an optional string property and written in Swift 4.

import StoreKit

extension SKProduct {
    
    var localizedPrice: String? {
        let formatter = NumberFormatter()
        formatter.numberStyle = .currency
        formatter.locale = priceLocale
        return formatter.string(from: price)
    }

}

Usage is much the same although it is no longer a function and you are responsible for unpacking the optional string:

NSLog("The price of this product is \(product.localizedPrice ?? "")")
// Example output: The price of this product is £0.99
Xcode 6 Essentials » « Yosemite WiFi Workaround: Airport Express and USB Ethernet Adapter

Want to keep up to date? Sign up to my free newsletter which will give you exclusive updates on all of my projects along with early access to future apps.