SBInAppPurchasing
SBInAppPurchasing 使内购(In-App Purchasing)变得容易。使用 Swift 编写。
特性
- 检查设备是否能够进行支付
- 请求内购列表
- 进行购买
- 恢复购买
- 回调和通知
请注意,目前我还没有测试过消耗型内购。
安装
SBinAppPurchasing 通过 CocoaPods 提供。要安装它,只需将以下行添加到 Podfile 中
pod "SBInAppPurchasing"
用法
####使用 SBInAppPurchasing 单例
import SBInAppPurchasing
let purchaser = SBInAppPurchasing.shared
####检查设备是否能够进行支付
某些设备可能无法进行支付,例如,如果不允许家长控制。应在购买前始终检查设备是否能够进行支付
if (purchaser.canMakePayments){
// Make a purchase
}
else{
// Alert user IAPs are disabled
}
####请求产品列表
// Products from previous requests are cached.
//Check the products optional if you do not want to refresh
if let products = purchaser.products{
// Products already downloaded
return
}
// The identifiers you set up in iTunes Connect
let identifiers = Set(["com.some.iap", "com.some.other.iap"])
purchaser.requestProducts(identifiers) { (products, error) in
if let error = error{
print("An error occurred: \(error.localizedDescription)")
return
}
if let products = products{
// Array of SKProduct received
}
}
####使用 SKProduct 进行购买,如果您已经调用过 requestProducts()
,则可以使用返回的产品之一进行购买
purchaser.purchase(product: someProduct) {
(success: Bool) in
if success {
// Unlock IAP
}
else{
// Show error
}
}
####使用标识符进行购买
也可以使用产品标识符而不调用 requestProducts()
来进行购买
purchaser.purchase(productWithIdentifier: "com.some.iap") {
(success: Bool) in
if success {
// Unlock IAP
}
else{
// Show error
}
}
####恢复购买
SBInAppPurchasing.shared.restorePurchases {
(identifer: String) in
if identifer == "com.some.iap" {
// Unlock IAP
}
}
####代理回调
使用传入的闭包是响应购买事件的最简单方式,但如果需要,实现了 SBInAppPurchasingDelegate
协议的对象也可以接收到购买事件的回调。
purchaser.delegate = someObject
// Recieves the following callbacks:
func purchaseCompleted(identifier: String)
func purchaseRestored(identifier: String)
func purchaseFailed(errorDescription: String)
####通知
或者,对象可以通过NSNotificationCenter监听通知
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(purchaseCompleted), name: .inAppPurchaseCompleted, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(purchaseRestored), name: .inAppPurchaseRestored, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(purchaseFailed), name: .inAppPurchaseFailed, object: nil)
func purchaseCompleted(notification: NSNotification){
let identifier = notification.object
}
func purchaseRestored(notification: NSNotification){
let identifier = notification.object
}
func purchaseFailed(notification: NSNotification){
let error = notification.object
}
作者
Steve Barnegren, [email protected]
关注我的twitter @SteveBarnegren
许可
SBInAppPurchasing 在MIT许可下可用。有关更多信息,请参阅LICENSE文件。