SwiftyStoreKit is a lightweight In App Purchases framework for iOS 8.0+, tvOS 9.0+ and OS X 10.10+, written in Swift.
Swift 2.2 / Xcode 7 compatibility is supported in the swift-2.2 branch.
Apple recommends to register a transaction observer as soon as the app starts:
Adding your app's observer at launch ensures that it will persist during all launches of your app, thus allowing your app to receive all the payment queue notifications.
SwiftyStoreKit supports this by calling completeTransactions()
when the app starts:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
SwiftyStoreKit.completeTransactions() { completedTransactions in
for completedTransaction in completedTransactions {
if completedTransaction.transactionState == .Purchased || completedTransaction.transactionState == .Restored {
print("purchased: \(completedTransaction.productId)")
}
}
}
return true
}
If there are any pending transactions at this point, these will be reported by the completion block so that the app state and UI can be updated.
SwiftyStoreKit.retrieveProductsInfo(["com.musevisions.SwiftyStoreKit.Purchase1"]) { result in
if let product = result.retrievedProducts.first {
let numberFormatter = NumberFormatter()
numberFormatter.locale = product.priceLocale
numberFormatter.numberStyle = .currency
let priceString = numberFormatter.string(from: product.price)
print("Product: \(product.localizedDescription), price: \(priceString)")
}
else if let invalidProductId = result.invalidProductIDs.first {
return alertWithTitle("Could not retrieve product info", message: "Invalid product identifier: \(invalidProductId)")
}
else {
print("Error: \(result.error)")
}
}
SwiftyStoreKit.purchaseProduct("com.musevisions.SwiftyStoreKit.Purchase1") { result in
switch result {
case .success(let productId):
print("Purchase Success: \(productId)")
case .error(let error):
print("Purchase Failed: \(error)")
}
}
SwiftyStoreKit.restorePurchases() { results in
if results.restoreFailedProducts.count > 0 {
print("Restore Failed: \(results.restoreFailedProducts)")
}
else if results.restoredProductIds.count > 0 {
print("Restore Success: \(results.restoredProductIds)")
}
else {
print("Nothing to Restore")
}
}
SwiftyStoreKit.verifyReceipt() { result in
if case .error(let error) = result {
if case .noReceiptData = error {
self.refreshReceipt()
}
}
}
func refreshReceipt() {
SwiftyStoreKit.refreshReceipt { result in
switch result {
case .success:
print("Receipt refresh success")
case .error(let error):
print("Receipt refresh failed: \(error)")
}
}
}
When using auto-renewable subscriptions, the shared secret can be specified like so:
SwiftyStoreKit.verifyReceipt(password: "your_shared_secret")
SwiftyStoreKit.verifyReceipt() { result in
switch result {
case .success(let receipt):
// Verify the purchase of Consumable or NonConsumable
let purchaseResult = SwiftyStoreKit.verifyPurchase(
productId: "com.musevisions.SwiftyStoreKit.Purchase1",
inReceipt: receipt
)
switch purchaseResult {
case .purchased(let expiresDate):
print("Product is purchased.")
case .notPurchased:
print("The user has never purchased this product")
}
case .Error(let error):
print("Receipt verification failed: \(error)")
}
}
Note that for consumable products, the receipt will only include the information for a couples of minutes after the purchase.
SwiftyStoreKit.verifyReceipt() { result in
switch result {
case .success(let receipt):
// Verify the purchase of a Subscription
let purchaseResult = SwiftyStoreKit.verifySubscription(
productId: "com.musevisions.SwiftyStoreKit.Subscription",
inReceipt: receipt,
validUntil: NSDate()
validDuration: 3600 * 24 * 30, // Non Renewing Subscription only
)
switch purchaseResult {
case .purchased(let expiresDate):
print("Product is valid until \(expiresDate)")
case .expired(let expiresDate):
print("Product is expired since \(expiresDate)")
case .notPurchased:
print("The user has never purchased this product")
}
case .error(let error):
print("Receipt verification failed: \(error)")
}
}
To test the expiration of a Non Renewing Subscription, you must indicate the validDuration
time interval in seconds.
NOTE: The framework provides a simple block based API with robust error handling on top of the existing StoreKit framework. It does NOT persist in app purchases data locally. It is up to clients to do this with a storage solution of choice (i.e. NSUserDefaults, CoreData, Keychain).
SwiftyStoreKit can be installed as a CocoaPod and builds as a Swift framework. To install, include this in your Podfile.
use_frameworks!
pod 'SwiftyStoreKit'
Once installed, just import SwiftyStoreKit
in your classes and you're good to go.
To integrate SwiftyStoreKit into your Xcode project using Carthage, specify it in your Cartfile:
github "bizz84/SwiftyStoreKit"
NOTE: Please ensure that you have the latest Carthage installed.
Following the release of Xcode 8 GM:
- The old Swift 2.2 code has been moved to the
swift-2.2
branch - The
swift-3.0
branch has been merged intomaster
As for versioning:
- Swift 3.0 work will be tagged as version
0.5.x
- Swift 2.2 work will be tagged as version
0.3.x
The project includes demo apps for iOS and OSX showing how to use SwiftyStoreKit. Note that the pre-registered in app purchases in the demo apps are for illustration purposes only and may not work as iTunes Connect may invalidate them.
- Super easy to use block based API
- Support for consumable, non-consumable in-app purchases
- Support for free, auto renewable and non renewing subscriptions
- Receipt verification
- iOS, tvOS and OS X compatible
- enum-based error handling
While SwiftyStoreKit tries handle concurrent purchase or restore purchases requests, it is not guaranteed that this will always work flawlessly.
This is in part because using a closure-based API does not map perfectly well with the lifecycle of payments in SKPaymentQueue
.
In real applications the following could happen:
- User starts a purchase
- User kills the app
- OS continues processing this, resulting in a failed or successful purchase
- App is restarted (payment queue is not updated yet)
- User starts another purchase (the old transaction may interfere with the new purchase)
To prevent situations like this from happening, a completeTransactions()
method has been added in version 0.2.8. This should be called when the app starts as it can take care of clearing the payment queue and notifying the app of the transactions that have finished.
The user can background the hosting application and change the Apple ID used with the App Store, then foreground the app. This has been observed to cause problems with SwiftyStoreKit - other IAP implementations may suffer from this as well.
- Port SwiftyStoreKit to Swift 3.0, compiles under Xcode 8 GM
- Increased minimum deployment target for OS X to version 10.10
- Fixed the
verifyReceipt()
method to use production environment by default. This falls back to the test environment if the receipt is a sandbox receipt.
- Added tvOS support
- Faster compilation time for
verifySubscription()
implementation
- Added support for verifying purchases and subscriptions. This includes consumable and non consumable purchases, auto-renewing, free and non-renewing subscriptions.
- The
purchaseProduct()
now takes an optionalapplicationUsername
string which can be used to help detect irregular activity on transactions. Read more about this on the Apple docs. - Updated
verifyReceipt()
so that the completion block is called on the main thread.
- Added
completeTransactions()
method to clear payment queue and return information about payments that have completed / failed.
- Fixed critical issue that was causing the callbacks for
purchaseProduct()
andrestorePurchases()
to get mixed up when multiple requests were running concurrently. Related issues: #3, #22, #26. Note that while code analysis and various testing scenarios indicate that this is now resolved, this has not yet been confirmed by the reporters of the issues.
- Retrieve multiple products info at once. Introduces the new
retrieveProductsInfo()
API call, which takes a set of product IDs and returns a struct with information about the corresponding SKProducts. Related issue #21
- The
restorePurchases()
completion closure has been changed to return all restored purchases in one call. Related issue #18
- Carthage compatible
- Fixed Swift 2.2 warnings
- Receipt verification
- OS X support
In order to make a purchase, two operations are needed:
-
Obtain the
SKProduct
corresponding to the productId that identifies the app purchase, viaSKProductRequest
. -
Submit the payment for that product via
SKPaymentQueue
.
The framework takes care of caching SKProducts so that future requests for the same SKProduct
don't need to perform a new SKProductRequest
.
SwiftyStoreKit wraps the delegate-based SKProductRequest
API with a block based class named InAppProductQueryRequest
, which returns a RetrieveResults
value with information about the obtained products:
public struct RetrieveResults {
public let retrievedProducts: Set<SKProduct>
public let invalidProductIDs: Set<String>
public let error: NSError?
}
This value is then surfaced back to the caller of the retrieveProductsInfo()
method the completion closure so that the client can update accordingly.
InAppProductPurchaseRequest
is a wrapper class for SKPaymentQueue
that can be used to purchase a product or restore purchases.
The class conforms to the SKPaymentTransactionObserver
protocol in order to receive transactions notifications from the payment queue. The following outcomes are defined for a purchase/restore action:
enum TransactionResult {
case purchased(productId: String)
case restored(productId: String)
case failed(error: NSError)
}
Depending on the operation, the completion closure for InAppProductPurchaseRequest
is then mapped to either a PurchaseResult
or a RestoreResults
value and returned to the caller.
Many thanks to phimage for adding OSX support and receipt verification.
It would be great to showcase apps using SwiftyStoreKit here. Pull requests welcome :)
- MDacne - Acne analysis and treatment
- Pixel Picker - Image Color Picker
- KType - Space shooter game
- iPic - Automatically upload images and save Markdown links
- iHosts - Perfect for editing /etc/hosts
Copyright (c) 2015-2016 Andrea Bizzotto [email protected]
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.