IAPHelper simply wraps the API of Apple's In-App Purchase using Swift. Very lightweight and easy to use.
var productIdentifiers = Set<ProductIdentifier>()
productIdentifiers.insert("product_id_1")
productIdentifiers.insert("product_id_2")
IAP.requestProducts(productIdentifiers) { (response, error) in
if let products = response?.products where !products.isEmpty {
// Get the valid products
} else if let invalidProductIdentifiers = response?.invalidProductIdentifiers {
// Some products id are invalid
} else {
// Some error happened
}
}
IAP.purchaseProduct(productIdentifier, handler: { (productIdentifier, error) in
if let identifier = productIdentifier {
// The product of 'productIdentifier' purchased.
} else if let error = error as? NSError {
if error.code == SKError.Code.paymentCancelled.rawValue {
// User cancelled
} else {
// Some error happened
}
}
})
IAP.restorePurchases { (productIdentifiers, error) in
if !productIdentifiers.isEmpty {
// Products restored
} else if let error = error as? NSError {
if error.code == SKError.Code.paymentCancelled.rawValue {
// User cancelled
} else {
// Some error happened
}
} else {
// No previous purchases were found.
}
}
IAP.validateReceipt(Constants.IAPSharedSecret) { (statusCode, products) in
if statusCode == ReceiptStatus.NoRecipt.rawValue {
// No Receipt in main bundle
} else {
// Get products with their expire date.
}
})
Note: IAPHelper directly validate with Apple's server. It's simple, but has risk. You decide to use your own server or not. Here's what Apple suggested:
Use a trusted server to communicate with the App Store. Using your own server lets you design your app to recognize and trust only your server, and lets you ensure that your server connects with the App Store server. It is not possible to build a trusted connection between a user’s device and the App Store directly because you don’t control either end of that connection.
Just copy IAPHelper.swift
to your project, and use it as the demo shows.
NOTE: You need to change the app bundle id and product id to your own. And also set your shared secret in Constants.swift
.
It would be great to show your apps using IAPHelper here. Pull requests welcome :)
This library can't help you understand the basic concepts for IAP. For it, please refer to these documents.