版本记录
版本号 | 时间 |
---|---|
V1.0 | 2019.01.25 星期五 |
前言
大家都知道,iOS虚拟商品如宝石、金币等都需要走内购,和苹果三七分成,如果这类商品不走内购那么上不去架或者上架以后被发现而被下架。最近有一个项目需要增加内购支付功能,所以最近又重新集成并整理了下,希望对大家有所帮助。感兴趣的可以参考上面几篇。
1. iOS内购IAP(一) —— 基础配置篇(一)
2. iOS内购IAP(二) —— 工程实践(一)
3. iOS内购IAP(三) —— 编程指南之关于内购(一)
4. iOS内购IAP(四) —— 编程指南之设计您的应用程序的产品(一)
5. iOS内购IAP(五) —— 编程指南之检索产品信息(一)
6. iOS内购IAP(六) —— 编程指南之请求支付(一)
7. iOS内购IAP(七) —— 编程指南之促进应用内购买(一)
8. iOS内购IAP(八) —— 编程指南之提供产品(一)
9. iOS内购IAP(九) —— 编程指南之处理订阅(一)
10. iOS内购IAP(十) —— 编程指南之恢复购买的产品(一)
11. iOS内购IAP(十一) —— 编程指南之准备App审核(一)
12. iOS内购IAP(十二) —— 一个详细的内购流程(一)
13. iOS内购IAP(十三) —— 一个详细的内购流程(二)
14. iOS内购IAP(十四) —— IAP的收据验证(一)
15. iOS内购IAP(十五) —— IAP的收据验证(二)
16. iOS内购IAP(十六) —— 添加介绍性定价选项(一)
源码
1. Swift
首先看下工程组织结构
接着看一下sb中的内容
接着就是代码
1. ViewController.swift
import UIKit
import StoreKit
class ViewController: UIViewController {
// MARK: - Instance Properties
var quotesContent: QuotesGroup!
var products: [SKProduct] = []
// MARK: - Outlets
@IBOutlet var quoteLbl: UILabel!
@IBOutlet var purchaseBttn: UIButton!
@IBOutlet var restoreBttn: UIButton!
// MARK: - Vie Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
loadQuotesFromFile()
PoohWisdomProducts.store.requestProducts { [weak self] success, products in
guard let self = self else { return }
guard success else {
let alertController = UIAlertController(title: "Failed to load list of products",
message: "Check logs for details",
preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "OK", style: .default))
self.present(alertController, animated: true, completion: nil)
return
}
self.products = products!
}
if PoohWisdomProducts.store.isProductPurchased(PoohWisdomProducts.poohWisdomSub) {
displayRandomQuote()
} else {
displayPurchaseQuotes()
}
}
func loadQuotesFromFile() {
guard let filePath = Bundle.main.path(forResource: "poohWisdom", ofType: "json") else {
fatalError("Quotes file path is incorrect!")
}
do {
let data = try Data(contentsOf: URL(fileURLWithPath: filePath))
quotesContent = try JSONDecoder().decode(QuotesGroup.self, from: data)
} catch {
fatalError(error.localizedDescription)
}
}
// MARK: - IBActions
@IBAction func purchaseSubscription(_ sender: Any) {
guard !products.isEmpty else {
print("Cannot purchase subscription because products is empty!")
return
}
PoohWisdomProducts.store.buyProduct(products[0]) { [weak self] success, productOd in
guard let self = self else { return }
guard success else {
let alertController = UIAlertController(title: "Failed to purchase product",
message: "Check logs for details",
preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "OK", style: .default))
self.present(alertController, animated: true, completion: nil)
return
}
self.displayRandomQuote()
}
}
@IBAction func restorePurchases(_ sender: Any) {
PoohWisdomProducts.store.restorePurchases()
}
// MARK: - Displaying Quotes
private func displayPurchaseQuotes() {
quoteLbl.text = "Wanna get random words of wisdom from Winnie the Pooh?\n\n" +
"Press the 'Purchase' button!\nWhat are you waiting for?!"
}
private func displayRandomQuote() {
let randNum = Int.random(in: 0 ..< quotesContent.quotes.count)
quoteLbl.text = quotesContent.quotes[randNum]
purchaseBttn.isHidden = true
restoreBttn.isHidden = true
}
}
2. IAPManager.swift
import StoreKit
public typealias ProductID = String
public typealias ProductsRequestCompletionHandler = (_ success: Bool, _ products: [SKProduct]?) -> Void
public typealias ProductPurchaseCompletionHandler = (_ success: Bool, _ productId: ProductID?) -> Void
// MARK: - IAPManager
public class IAPManager: NSObject {
private let productIDs: Set<ProductID>
private var purchasedProductIDs: Set<ProductID>
private var productsRequest: SKProductsRequest?
private var productsRequestCompletionHandler: ProductsRequestCompletionHandler?
private var productPurchaseCompletionHandler: ProductPurchaseCompletionHandler?
public init(productIDs: Set<ProductID>) {
self.productIDs = productIDs
self.purchasedProductIDs = productIDs.filter { productID in
let purchased = UserDefaults.standard.bool(forKey: productID)
if purchased {
print("Previously purchased: \(productID)")
} else {
print("Not purchased: \(productID)")
}
return purchased
}
super.init()
SKPaymentQueue.default().add(self)
}
}
// MARK: - StoreKit API
extension IAPManager {
public func requestProducts(_ completionHandler: @escaping ProductsRequestCompletionHandler) {
productsRequest?.cancel()
productsRequestCompletionHandler = completionHandler
productsRequest = SKProductsRequest(productIdentifiers: productIDs)
productsRequest!.delegate = self
productsRequest!.start()
}
public func buyProduct(_ product: SKProduct, _ completionHandler: @escaping ProductPurchaseCompletionHandler) {
productPurchaseCompletionHandler = completionHandler
print("Buying \(product.productIdentifier)...")
let payment = SKPayment(product: product)
SKPaymentQueue.default().add(payment)
}
public func isProductPurchased(_ productID: ProductID) -> Bool {
return purchasedProductIDs.contains(productID)
}
public class func canMakePayments() -> Bool {
return SKPaymentQueue.canMakePayments()
}
public func restorePurchases() {
SKPaymentQueue.default().restoreCompletedTransactions()
}
}
// MARK: - SKProductsRequestDelegate
extension IAPManager: SKProductsRequestDelegate {
public func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) {
print("Loaded list of products...")
let products = response.products
guard !products.isEmpty else {
print("Product list is empty...!")
print("Did you configure the project and set up the IAP?")
productsRequestCompletionHandler?(false, nil)
return
}
productsRequestCompletionHandler?(true, products)
clearRequestAndHandler()
for p in products {
print("Found product: \(p.productIdentifier) \(p.localizedTitle) \(p.price.floatValue)")
}
}
public func request(_ request: SKRequest, didFailWithError error: Error) {
print("Failed to load list of products.")
print("Error: \(error.localizedDescription)")
productsRequestCompletionHandler?(false, nil)
clearRequestAndHandler()
}
private func clearRequestAndHandler() {
productsRequest = nil
productsRequestCompletionHandler = nil
}
}
// MARK: - SKPaymentTransactionObserver
extension IAPManager: SKPaymentTransactionObserver {
public func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
for transaction in transactions {
switch (transaction.transactionState) {
case .purchased:
complete(transaction: transaction)
break
case .failed:
fail(transaction: transaction)
break
case .restored:
restore(transaction: transaction)
break
case .deferred:
break
case .purchasing:
break
}
}
}
private func complete(transaction: SKPaymentTransaction) {
print("complete...")
productPurchaseCompleted(identifier: transaction.payment.productIdentifier)
SKPaymentQueue.default().finishTransaction(transaction)
}
private func restore(transaction: SKPaymentTransaction) {
guard let productIdentifier = transaction.original?.payment.productIdentifier else { return }
print("restore... \(productIdentifier)")
productPurchaseCompleted(identifier: productIdentifier)
SKPaymentQueue.default().finishTransaction(transaction)
}
private func fail(transaction: SKPaymentTransaction) {
print("fail...")
if let transactionError = transaction.error as NSError?,
let localizedDescription = transaction.error?.localizedDescription,
transactionError.code != SKError.paymentCancelled.rawValue {
print("Transaction Error: \(localizedDescription)")
}
productPurchaseCompletionHandler?(false, nil)
SKPaymentQueue.default().finishTransaction(transaction)
clearHandler()
}
private func productPurchaseCompleted(identifier: ProductID?) {
guard let identifier = identifier else { return }
purchasedProductIDs.insert(identifier)
UserDefaults.standard.set(true, forKey: identifier)
productPurchaseCompletionHandler?(true, identifier)
clearHandler()
}
private func clearHandler() {
productPurchaseCompletionHandler = nil
}
}
3. PoohWisdomProducts.swift
import Foundation
public struct PoohWisdomProducts {
public static let poohWisdomSub = "com.razeware.poohWisdom.monthlySub"
public static let store = IAPManager(productIDs: PoohWisdomProducts.productIDs)
private static let productIDs: Set<ProductID> = [PoohWisdomProducts.poohWisdomSub]
}
public func resourceNameForProductIdentifier(_ productIdentifier: String) -> String? {
return productIdentifier.components(separatedBy: ".").last
}
4. QuotesGroup.swift
public struct QuotesGroup: Decodable {
public let quotes: [String]
}
后记
本篇主要讲述了添加介绍性定价选项,感兴趣的给个赞或者关注~~~