Ben Dodson

Freelance iOS, 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.69

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.

Xcode 6 Essentials » « Yosemite WiFi Workaround: Airport Express and USB Ethernet Adapter