iOS內(nèi)購IAP(十三) —— 一個詳細(xì)的內(nèi)購流程(二)

版本記錄

版本號 時間
V1.0 2018.08.14

前言

大家都知道,iOS虛擬商品如寶石、金幣等都需要走內(nèi)購,和蘋果三七分成,如果這類商品不走內(nèi)購那么上不去架或者上架以后被發(fā)現(xiàn)而被下架。最近有一個項(xiàng)目需要增加內(nèi)購支付功能,所以最近又重新集成并整理了下,希望對大家有所幫助。感興趣的可以參考上面幾篇。
1. iOS內(nèi)購IAP(一) —— 基礎(chǔ)配置篇(一)
2. iOS內(nèi)購IAP(二) —— 工程實(shí)踐(一)
3. iOS內(nèi)購IAP(三) —— 編程指南之關(guān)于內(nèi)購(一)
4. iOS內(nèi)購IAP(四) —— 編程指南之設(shè)計您的應(yīng)用程序的產(chǎn)品(一)
5. iOS內(nèi)購IAP(五) —— 編程指南之檢索產(chǎn)品信息(一)
6. iOS內(nèi)購IAP(六) —— 編程指南之請求支付(一)
7. iOS內(nèi)購IAP(七) —— 編程指南之促進(jìn)應(yīng)用內(nèi)購買(一)
8. iOS內(nèi)購IAP(八) —— 編程指南之提供產(chǎn)品(一)
9. iOS內(nèi)購IAP(九) —— 編程指南之處理訂閱(一)
10. iOS內(nèi)購IAP(十) —— 編程指南之恢復(fù)購買的產(chǎn)品(一)
11. iOS內(nèi)購IAP(十一) —— 編程指南之準(zhǔn)備App審核(一)
12. iOS內(nèi)購IAP(十二) —— 一個詳細(xì)的內(nèi)購流程(一)

Project Configuration - 工程配置

為了使一切正常工作,應(yīng)用程序中的bundle identifierproduct identifiers與您在Developer CenterApp Store Connect中創(chuàng)建的標(biāo)識符和產(chǎn)品標(biāo)識符相匹配非常重要。

回到Xcode中,在Project導(dǎo)航器中選擇RazeFaces項(xiàng)目,然后在Targets下再次選擇它。 選擇General選項(xiàng)卡,將您的Team切換到正確的團(tuán)隊(duì),然后輸入您之前使用的bundle ID

接下來選擇Capabilities選項(xiàng)卡。 向下滾動到In-App Purchase并將開關(guān)切換到ON

注意:如果IAP未顯示在列表中,請確保在Xcode
preferences的Accounts部分中使用您用于創(chuàng)建應(yīng)用程序ID的Apple ID登錄。

打開RazeFaceProducts.swift。 請注意,您創(chuàng)建的IAP產(chǎn)品有一個占位符引用:SwiftShopping。 將其替換為您在App Store Connect中配置的完整Product ID - 例如:

public static let SwiftShopping = "com.theNameYouPickedEarlier.razefaces.swiftshopping"

注意:可以從Web服務(wù)器中提取產(chǎn)品標(biāo)識符列表,以便可以動態(tài)添加新的IAP,而不需要更新應(yīng)用程序。 本教程簡單易用,使用硬編碼的產(chǎn)品標(biāo)識符。


Listing In-App Purchases - IAP列表

RazeFaceProductsstore屬性是IAPHelper的一個實(shí)例。 如前所述,此對象與StoreKit API交互以列出和執(zhí)行購買。 您的第一個任務(wù)是更新IAPHelper以檢索IAP列表 - 目前只有一個 - 來自Apple的服務(wù)器。

打開IAPHelper.swift。 在該類的頂部,添加以下私有屬性:

private let productIdentifiers: Set<ProductIdentifier>

接下來,在調(diào)用super.init()之前將以下內(nèi)容添加到init(productIds :)

productIdentifiers = productIds

通過傳入一組產(chǎn)品標(biāo)識符來創(chuàng)建IAPHelper實(shí)例。 這就是RazeFaceProducts創(chuàng)建其store實(shí)例的方式。

接下來,在剛才添加的那個下添加其他私有屬性:

private var purchasedProductIdentifiers: Set<ProductIdentifier> = []
private var productsRequest: SKProductsRequest?
private var productsRequestCompletionHandler: ProductsRequestCompletionHandler?

purchaseProductIdentifiers跟蹤已購買的商品。 SKProductsRequest委托使用其他兩個屬性來執(zhí)行對Apple服務(wù)器的請求。

接下來,仍然在IAPHelper.swift中用以下代碼替換requestProducts(_ :)的實(shí)現(xiàn):

public func requestProducts(completionHandler: @escaping ProductsRequestCompletionHandler) {
  productsRequest?.cancel()
  productsRequestCompletionHandler = completionHandler

  productsRequest = SKProductsRequest(productIdentifiers: productIdentifiers)
  productsRequest!.delegate = self
  productsRequest!.start()
}

此代碼保存用戶的完成處理程序以供將來執(zhí)行。 然后,它通過SKProductsRequest對象創(chuàng)建并向Apple發(fā)起請求。 有一個問題:代碼將IAPHelper聲明為請求的代理,但它還不遵守SKProductsRequestDelegate協(xié)議。

要解決此問題,請?jiān)谧詈笠粋€大括號之后將以下擴(kuò)展名添加到IAPHelper.swift的最后:

// MARK: - SKProductsRequestDelegate

extension IAPHelper: SKProductsRequestDelegate {

  public func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) {
    print("Loaded list of products...")
    let products = response.products
    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
  }
}

此擴(kuò)展用于通過實(shí)現(xiàn)SKProductsRequestDelegate協(xié)議所需的兩種方法從Apple服務(wù)器獲取產(chǎn)品列表,標(biāo)題,描述和價格。

成功檢索列表時調(diào)用productsRequest(_:didReceive :)。 它接收一組SKProduct對象并將它們傳遞給先前保存的完成處理程序。 處理程序使用新數(shù)據(jù)重新加載表。 如果出現(xiàn)問題,則調(diào)用request(_:didFailWithError :)。 在任何一種情況下,當(dāng)請求完成時,請求和完成處理程序都將使用clearRequestAndHandler()清除。

Build并運(yùn)行。table view中顯示了產(chǎn)品列表(目前只有一個)! 這需要一些工作,但還是實(shí)現(xiàn)了。

注意:您可以在iOS模擬器和物理iOS設(shè)備上顯示IAP產(chǎn)品,但如果您要測試購買或恢復(fù)購買,則只能在物理設(shè)備上執(zhí)行此操作。 更多相關(guān)信息,請參閱下面的購買部分。

注意:如果運(yùn)行不成功且您沒有看到任何產(chǎn)品,那么有很多事情需要檢查。

  • 項(xiàng)目的Bundle ID是否與iOS Development Center的App ID相匹配?
  • 在制作SKProductRequest時是否使用完整的product ID? (檢查RazeFaceProductsproductIdentifiers屬性。)
  • Paid Applications Contract是否對iTunes Connect有效?他們提交申請的時間可能需要數(shù)小時到數(shù)天才能從待定到接受。
  • 自從將產(chǎn)品添加到App Store Connect后,您有幾個小時的時間嗎?產(chǎn)品添加可能會立即生效或可能需要一些時間。
  • 檢查Apple Developer System Status?;蛘?,嘗試此鏈接this link。如果它沒有響應(yīng)狀態(tài)值,則iTunes沙盒可能已關(guān)閉。 Apple的 Validating Receipts With the App Store文檔中說明了狀態(tài)代碼。
  • 是否為App ID啟用了IAP? (你之前選擇過Cleared for Sale嗎?)
  • 您是否嘗試從設(shè)備中刪除該應(yīng)用并重新安裝?

Purchased Items - 購買項(xiàng)目

您希望能夠確定已購買的商品。 為此,您將使用之前添加的purchaseProductIdentifiers屬性。 如果此集合中包含產(chǎn)品標(biāo)識符,則用戶已購買該項(xiàng)目。 檢查這個的方法很簡單。

IAPHelper.swift中,使用以下內(nèi)容替換isProductPurchased(_ :)中的return語句:

return purchasedProductIdentifiers.contains(productIdentifier)

在本地保存購買狀態(tài)可以減少每次應(yīng)用啟動時向Apple服務(wù)器請求此類數(shù)據(jù)的需求。 purchaseProductIdentifiers使用UserDefaults保存。

仍在IAPHelper.swift中,將init(productIds :)替換為以下內(nèi)容:

public init(productIds: Set<ProductIdentifier>) {
  productIdentifiers = productIds
  for productIdentifier in productIds {
    let purchased = UserDefaults.standard.bool(forKey: productIdentifier)
    if purchased {
      purchasedProductIdentifiers.insert(productIdentifier)
      print("Previously purchased: \(productIdentifier)")
    } else {
      print("Not purchased: \(productIdentifier)")
    }
  }
  super.init()
}

對于每個產(chǎn)品標(biāo)識符,檢查該值是否存儲在UserDefaults中。 如果是,則將標(biāo)識符插入到purchaseProductIdentifiers的set中。 之后,您將在購買后向set中添加標(biāo)識符。

注意:User defaults可能不是在實(shí)際應(yīng)用程序中存儲有關(guān)已購買產(chǎn)品的信息的最佳位置。 越獄設(shè)備的所有者可以輕松訪問您應(yīng)用的UserDefaults plist,并將其修改為unlock購買。 如果這種事情與您有關(guān),那么值得查看Apple關(guān)于Validating App Store Receipts的文檔 - 這可以讓您驗(yàn)證用戶是否進(jìn)行了特定購買。


Making Purchases (Show Me The Money!) - 進(jìn)行購買

可以了解用戶購買的產(chǎn)品很好,但您仍然需要首先進(jìn)行購買! 實(shí)施購買能力是合乎邏輯的下一步。

仍然在IAPHelper.swift中,用以下內(nèi)容替換buyProduct(_ :)

public func buyProduct(_ product: SKProduct) {
  print("Buying \(product.productIdentifier)...")
  let payment = SKPayment(product: product)
  SKPaymentQueue.default().add(payment)
}

這將使用SKProduct(從Apple服務(wù)器檢索)創(chuàng)建支付對象以添加到支付隊(duì)列。 該代碼使用名為default()的單例SKPaymentQueue對象。錢在銀行里。 不是嗎? 你怎么知道付款是否通過?

通過讓IAPHelper觀察SKPaymentQueue上發(fā)生的交易來實(shí)現(xiàn)付款驗(yàn)證。 在將IAPHelper設(shè)置為SKPaymentQueue交易觀察器之前,該類必須遵循SKPaymentTransactionObserver協(xié)議。

轉(zhuǎn)到IAPHelper.swift的最底部(在最后一個大括號之后)并添加以下擴(kuò)展名:

// MARK: - SKPaymentTransactionObserver
 
extension IAPHelper: 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...")
    deliverPurchaseNotificationFor(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)")
    deliverPurchaseNotificationFor(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)")
      }

    SKPaymentQueue.default().finishTransaction(transaction)
  }
 
  private func deliverPurchaseNotificationFor(identifier: String?) {
    guard let identifier = identifier else { return }
 
    purchasedProductIdentifiers.insert(identifier)
    UserDefaults.standard.set(true, forKey: identifier)
    NotificationCenter.default.post(name: .IAPHelperPurchaseNotification, object: identifier)
  }
}

這是很多代碼! 詳細(xì)的審查是有序的。 幸運(yùn)的是,每種方法都很短。

paymentQueue(_:updatedTransactions :)是協(xié)議實(shí)際需要的唯一方法。 當(dāng)一個或多個交易狀態(tài)發(fā)生變化時,它會被調(diào)用。 此方法評估更新交易數(shù)組中每個交易的狀態(tài),并調(diào)用相關(guān)的幫助方法:complete(transaction:)restore(transaction:)fail(transaction:)。

如果交易已完成或已恢復(fù),則會將其添加到購買set中并將標(biāo)識符保存在UserDefaults中。 它還會在該事務(wù)中發(fā)布通知,以便應(yīng)用程序中的任何感興趣的對象都可以監(jiān)聽它以執(zhí)行更新用戶界面等操作。 最后,在成功或失敗的情況下,它將交易標(biāo)記為已完成。

剩下的就是將IAPHelper作為支付交易觀察者。 仍然在IAPHelper.swift中,返回init(productIds :)并在super.init()之后添加以下行。

SKPaymentQueue.default().add(self)

Making a Sandbox Purchase - 進(jìn)行沙盒購買

Build并運(yùn)行應(yīng)用程序 - 但要測試購買,您必須在設(shè)備上運(yùn)行它。 之前創(chuàng)建的沙箱測試儀可用于執(zhí)行購買而無需收費(fèi)。以下是如何使用測試人員帳戶:

轉(zhuǎn)到您的iPhone并確保您已退出正常的App Store帳戶。 要執(zhí)行此操作,請轉(zhuǎn)到Settings應(yīng)用,然后點(diǎn)按iTunes & App Store。

點(diǎn)按您的iCloud帳戶名稱,然后點(diǎn)按Sign Out。 此時,實(shí)際上并未使用沙箱用戶登錄。 一旦您嘗試在示例應(yīng)用程序中購買IAP,系統(tǒng)將提示您執(zhí)行此操作。

連接您的設(shè)備,Build并運(yùn)行! 您會在應(yīng)用中看到您的產(chǎn)品。 要開始購買,請點(diǎn)按Buy按鈕。

將出現(xiàn)一個提示您登錄的彈窗。點(diǎn)擊Use Existing Apple ID,然后輸入您之前創(chuàng)建的沙箱測試人員帳戶的登錄詳細(xì)信息。

點(diǎn)按Buy確認(rèn)購買。 彈窗視圖顯示正在沙盒中進(jìn)行購買,以提醒您不會向您收取費(fèi)用。

最后,將出現(xiàn)一個彈窗視圖,確認(rèn)購買成功。 購買過程完成后,購買項(xiàng)目旁邊會出現(xiàn)一個復(fù)選標(biāo)記。 點(diǎn)擊purchased item即可享受新的RazeFace

最后你會看到這個Swift Shopping RazeFace。


Restoring Purchases - 恢復(fù)購買

如果用戶刪除并重新安裝應(yīng)用程序或?qū)⑵浒惭b在其他設(shè)備上,則他們需要能夠訪問以前購買的項(xiàng)目。 事實(shí)上,如果App無法恢復(fù)非消費(fèi)品購買,Apple可能會拒絕該應(yīng)用。

作為購買交易觀察者,IAPHelper已經(jīng)在恢復(fù)購買時得到通知。 下一步是通過恢復(fù)購買來對此通知做出反應(yīng)。

打開IAPHelper.swift并滾動到文件的底部。 在StoreKit API extension中,將restorePurchases()替換為以下內(nèi)容:

public func restorePurchases() {
  SKPaymentQueue.default().restoreCompletedTransactions()
}

那太簡單了! 您已經(jīng)設(shè)置了事務(wù)觀察器并實(shí)現(xiàn)了方法來處理上一步中的恢復(fù)事務(wù)。

要對此進(jìn)行測試,請?jiān)谏弦徊街型瓿少徺I后,從設(shè)備中刪除該應(yīng)用。 再次構(gòu)建并運(yùn)行,然后點(diǎn)擊右上角的Restore。 您應(yīng)該會在先前購買的產(chǎn)品旁邊看到復(fù)選標(biāo)記。


Payment Permissions - 支付許可

某些設(shè)備和帳戶可能不允許進(jìn)行應(yīng)用內(nèi)購買。 例如,如果將父級控件設(shè)置為禁止它,則會發(fā)生這種情況。 Apple要求優(yōu)雅地處理這種情況。 不這樣做可能會導(dǎo)致應(yīng)用拒絕。

再次打開IAPHelper.swift。 在StoreKit API extension中,將canMakePayments()中的return語句替換為以下行:

return SKPaymentQueue.canMakePayments()

根據(jù)canMakePayments()返回的值,產(chǎn)品單元的行為應(yīng)該不同。 例如,如果canMakePayments()返回false,則不應(yīng)顯示Buy按鈕,并且應(yīng)將價格替換為Not Available

要完成此任務(wù),請打開ProductCell.swift并使用以下內(nèi)容替換product屬性的didSet處理程序的整個實(shí)現(xiàn):

didSet {
  guard let product = product else { return }
 
  textLabel?.text = product.localizedTitle
 
  if RazeFaceProducts.store.isProductPurchased(product.productIdentifier) {
    accessoryType = .checkmark
    accessoryView = nil
    detailTextLabel?.text = ""
  } else if IAPHelper.canMakePayments() {
    ProductCell.priceFormatter.locale = product.priceLocale
    detailTextLabel?.text = ProductCell.priceFormatter.string(from: product.price)
 
    accessoryType = .none
    accessoryView = self.newBuyButton()
  } else {
    detailTextLabel?.text = "Not available"
  }
}

當(dāng)無法使用設(shè)備付款時,此實(shí)施將顯示更合適的信息。

Apple有一個很棒的頁面講述In-App Purchase for Developers:面向開發(fā)人員的應(yīng)用內(nèi)購買。 它匯集了所有相關(guān)文檔和WWDC視頻的鏈接。

IAP可以成為您業(yè)務(wù)模式的重要組成部分。 明智地使用它們并確保遵循有關(guān)恢復(fù)購買和優(yōu)雅處理失敗的指導(dǎo)方針,您將走向成功的道路!


源碼

下面給出Swift版本的源碼。

1. IAPHelper.swift
import StoreKit

public typealias ProductIdentifier = String
public typealias ProductsRequestCompletionHandler = (_ success: Bool, _ products: [SKProduct]?) -> Void

extension Notification.Name {
  static let IAPHelperPurchaseNotification = Notification.Name("IAPHelperPurchaseNotification")
}

open class IAPHelper: NSObject  {
  
  private let productIdentifiers: Set<ProductIdentifier>
  private var purchasedProductIdentifiers: Set<ProductIdentifier> = []
  private var productsRequest: SKProductsRequest?
  private var productsRequestCompletionHandler: ProductsRequestCompletionHandler?
  
  public init(productIds: Set<ProductIdentifier>) {
    productIdentifiers = productIds
    for productIdentifier in productIds {
      let purchased = UserDefaults.standard.bool(forKey: productIdentifier)
      if purchased {
        purchasedProductIdentifiers.insert(productIdentifier)
        print("Previously purchased: \(productIdentifier)")
      } else {
        print("Not purchased: \(productIdentifier)")
      }
    }
    super.init()

    SKPaymentQueue.default().add(self)
  }
}

// MARK: - StoreKit API

extension IAPHelper {
  
  public func requestProducts(_ completionHandler: @escaping ProductsRequestCompletionHandler) {
    productsRequest?.cancel()
    productsRequestCompletionHandler = completionHandler

    productsRequest = SKProductsRequest(productIdentifiers: productIdentifiers)
    productsRequest!.delegate = self
    productsRequest!.start()
  }

  public func buyProduct(_ product: SKProduct) {
    print("Buying \(product.productIdentifier)...")
    let payment = SKPayment(product: product)
    SKPaymentQueue.default().add(payment)
  }

  public func isProductPurchased(_ productIdentifier: ProductIdentifier) -> Bool {
    return purchasedProductIdentifiers.contains(productIdentifier)
  }
  
  public class func canMakePayments() -> Bool {
    return SKPaymentQueue.canMakePayments()
  }
  
  public func restorePurchases() {
    SKPaymentQueue.default().restoreCompletedTransactions()
  }
}

// MARK: - SKProductsRequestDelegate

extension IAPHelper: SKProductsRequestDelegate {

  public func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) {
    print("Loaded list of products...")
    let products = response.products
    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 IAPHelper: 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...")
    deliverPurchaseNotificationFor(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)")
    deliverPurchaseNotificationFor(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)")
      }

    SKPaymentQueue.default().finishTransaction(transaction)
  }

  private func deliverPurchaseNotificationFor(identifier: String?) {
    guard let identifier = identifier else { return }

    purchasedProductIdentifiers.insert(identifier)
    UserDefaults.standard.set(true, forKey: identifier)
    NotificationCenter.default.post(name: .IAPHelperPurchaseNotification, object: identifier)
  }
}
2. RazeFaceProducts.swift
import Foundation

public struct RazeFaceProducts {
  
  public static let SwiftShopping = "com.razeware.razefaces.swiftshopping"
  
  private static let productIdentifiers: Set<ProductIdentifier> = [RazeFaceProducts.SwiftShopping]

  public static let store = IAPHelper(productIds: RazeFaceProducts.productIdentifiers)
}

func resourceNameForProductIdentifier(_ productIdentifier: String) -> String? {
  return productIdentifier.components(separatedBy: ".").last
}
3. MasterViewController.swift
import UIKit
import StoreKit

class MasterViewController: UITableViewController {
  
  let showDetailSegueIdentifier = "showDetail"
  
  var products: [SKProduct] = []
  
  override func shouldPerformSegue(withIdentifier identifier: String, sender: Any?) -> Bool {
    if identifier == showDetailSegueIdentifier {
      guard let indexPath = tableView.indexPathForSelectedRow else {
        return false
      }
      
      let product = products[(indexPath as NSIndexPath).row]
      
      return RazeFaceProducts.store.isProductPurchased(product.productIdentifier)
    }
    
    return true
  }

  override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == showDetailSegueIdentifier {
      guard let indexPath = tableView.indexPathForSelectedRow else { return }
      
      let product = products[(indexPath as NSIndexPath).row]
      
      if let name = resourceNameForProductIdentifier(product.productIdentifier),
             let detailViewController = segue.destination as? DetailViewController {
        let image = UIImage(named: name)
        detailViewController.image = image
      }
    }
  }

  override func viewDidLoad() {
    super.viewDidLoad()
    
    title = "RazeFaces"
    
    refreshControl = UIRefreshControl()
    refreshControl?.addTarget(self, action: #selector(MasterViewController.reload), for: .valueChanged)
    
    let restoreButton = UIBarButtonItem(title: "Restore",
                                        style: .plain,
                                        target: self,
                                        action: #selector(MasterViewController.restoreTapped(_:)))
    navigationItem.rightBarButtonItem = restoreButton
    
    NotificationCenter.default.addObserver(self, selector: #selector(MasterViewController.handlePurchaseNotification(_:)),
                                           name: .IAPHelperPurchaseNotification,
                                           object: nil)
  }
  
  override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    reload()
  }
  
  @objc func reload() {
    products = []
    
    tableView.reloadData()
    
    RazeFaceProducts.store.requestProducts{ [weak self] success, products in
      guard let self = self else { return }
      if success {
        self.products = products!
        
        self.tableView.reloadData()
      }
      
      self.refreshControl?.endRefreshing()
    }
  }
  
  @objc func restoreTapped(_ sender: AnyObject) {
    RazeFaceProducts.store.restorePurchases()
  }

  @objc func handlePurchaseNotification(_ notification: Notification) {
    guard
      let productID = notification.object as? String,
      let index = products.index(where: { product -> Bool in
        product.productIdentifier == productID
      })
    else { return }

    tableView.reloadRows(at: [IndexPath(row: index, section: 0)], with: .fade)
  }
}

// MARK: - UITableViewDataSource

extension MasterViewController {
  
  override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return products.count
  }

  override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! ProductCell
    
    let product = products[(indexPath as NSIndexPath).row]
    
    cell.product = product
    cell.buyButtonHandler = { product in
      RazeFaceProducts.store.buyProduct(product)
    }
    
    return cell
  }
}
4. DetailViewController.swift
import UIKit

class DetailViewController: UIViewController {
  
  @IBOutlet weak var imageView: UIImageView?
  
  var image: UIImage? {
    didSet {
      configureView()
    }
  }
  
  override func viewDidLoad() {
    super.viewDidLoad()
    
    configureView()
  }
  
  func configureView() {
    imageView?.image = image
  }
}
5. ProductCell.swift
import UIKit
import StoreKit

class ProductCell: UITableViewCell {
  static let priceFormatter: NumberFormatter = {
    let formatter = NumberFormatter()
    
    formatter.formatterBehavior = .behavior10_4
    formatter.numberStyle = .currency
    
    return formatter
  }()
  
  var buyButtonHandler: ((_ product: SKProduct) -> Void)?
  
  var product: SKProduct? {
    didSet {
      guard let product = product else { return }

      textLabel?.text = product.localizedTitle

      if RazeFaceProducts.store.isProductPurchased(product.productIdentifier) {
        accessoryType = .checkmark
        accessoryView = nil
        detailTextLabel?.text = ""
      } else if IAPHelper.canMakePayments() {
        ProductCell.priceFormatter.locale = product.priceLocale
        detailTextLabel?.text = ProductCell.priceFormatter.string(from: product.price)

        accessoryType = .none
        accessoryView = self.newBuyButton()
      } else {
        detailTextLabel?.text = "Not available"
      }
    }
  }
  
  override func prepareForReuse() {
    super.prepareForReuse()
    
    textLabel?.text = ""
    detailTextLabel?.text = ""
    accessoryView = nil
  }
  
  func newBuyButton() -> UIButton {
    let button = UIButton(type: .system)
    button.setTitleColor(tintColor, for: .normal)
    button.setTitle("Buy", for: .normal)
    button.addTarget(self, action: #selector(ProductCell.buyButtonTapped(_:)), for: .touchUpInside)
    button.sizeToFit()
    
    return button
  }
  
  @objc func buyButtonTapped(_ sender: AnyObject) {
    buyButtonHandler?(product!)
  }
}

后記

本篇主要講述了一個詳細(xì)的內(nèi)購流程,感興趣的給個贊或者關(guān)注~~~

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容