Skip to content

Commit

Permalink
Minor refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
iridescent-dev committed May 29, 2020
1 parent f58e2a9 commit dc8e1d3
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 28 deletions.
4 changes: 2 additions & 2 deletions Sources/InAppPurchaseLib/InAppPurchase.swift
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import StoreKit
/// The main class of the library.
public class InAppPurchase: NSObject, InAppPurchaseLib {
/// InAppPurchaseLib version number.
internal static let versionNumber = "1.0.3"
internal static let versionNumber = "1.0.4"
/// The initialize function has been called.
internal static var initialized: Bool {
return !iapProducts.isEmpty && iapPurchaseDelegate != nil && validatorUrlString != nil
Expand Down Expand Up @@ -182,7 +182,7 @@ public class InAppPurchase: NSObject, InAppPurchaseLib {
callback(IAPRefreshResult(state: .failed, iapError: IAPError(code: .libraryNotInitialized)))
return
}
IAPReceiptService.shared.forceRefresh(callback: callback)
IAPReceiptService.shared.refreshReceipt(callback: callback)
}

/// Finish all transactions for the product.
Expand Down
2 changes: 1 addition & 1 deletion Sources/InAppPurchaseLib/InAppPurchaseLib.swift
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ public protocol InAppPurchaseLib {
/// Stop observing the payment queue, when the application will terminate, for proper cleanup.
static func stop() -> Void

/// Refresh Product list and user Receipt.
/// Load products and refresh the status of purchases and subscriptions.
/// - Parameter callback: The function that will be called after processing.
/// - See also:`IAPRefreshResult`
static func refresh(callback: @escaping IAPRefreshCallback) -> Void
Expand Down
51 changes: 26 additions & 25 deletions Sources/InAppPurchaseLib/Purchase/IAPReceiptService.swift
Original file line number Diff line number Diff line change
Expand Up @@ -25,23 +25,34 @@ class IAPReceiptService: NSObject, SKRequestDelegate {


/* MARK: - Main methods */
// Validate the App Store Receipt
func refresh(callback: @escaping IAPRefreshCallback){
// Refresh the App Store Receipt.
func refreshReceipt(callback: @escaping IAPRefreshCallback){
self.refreshCallbackBlock = callback
validateReceipt()
refreshAppStoreReceipt()
}
// Refresh the App Store Receipt
func forceRefresh(callback: @escaping IAPRefreshCallback){
// Refresh the status of purchases and subscriptions.
func refresh(callback: @escaping IAPRefreshCallback){
self.refreshCallbackBlock = callback
refreshReceipt()
validateAppStoreReceipt()
}
// Validate the App Store Receipt after a purchase.
// Refresh the status of purchases and subscriptions after a purchase.
func refreshAfterPurchased(callback: @escaping IAPPurchaseCallback, purchasingProductIdentifier: String){
self.purchaseCallbackBlock = callback
self.purchaseProductIdentifier = purchasingProductIdentifier
validateReceipt()
validateAppStoreReceipt()
}

// Refresh is required if a subscription has just expired.
func refreshRequired() -> Bool {
for productIdentifier in InAppPurchase.iapProducts.filter({ $0.productType == .autoRenewableSubscription }).map({ $0.productIdentifier }) {
if hasJustExpiredSubscription(for: productIdentifier) {
return true
}
}
return false
}

// MARK: - Status of purchases and subscriptions
// Checks if the user has already purchased at least one product.
func hasAlreadyPurchased() -> Bool{
return IAPStorageService.getBool(forKey: HAS_ALREADY_PURCHASED_KEY)
Expand Down Expand Up @@ -72,17 +83,6 @@ class IAPReceiptService: NSObject, SKRequestDelegate {
return nextExpiryDate == nil && expiryDate.addingTimeInterval(120) > Date()
}

// Refresh is required if a subscription has just expired.
func refreshRequired() -> Bool {
for productIdentifier in InAppPurchase.iapProducts.filter({ $0.productType == .autoRenewableSubscription }).map({ $0.productIdentifier }) {
if hasJustExpiredSubscription(for: productIdentifier) {
return true
}
}
return false
}


// Returns the latest purchased date for a given product.
func getPurchaseDate(for productIdentifier: String) -> Date? {
return IAPStorageService.getDate(forKey: PURCHASE_DATE_KEY, productIdentifier: productIdentifier)
Expand All @@ -103,11 +103,12 @@ class IAPReceiptService: NSObject, SKRequestDelegate {
return IAPStorageService.getDate(forKey: NEXT_EXPIRY_DATE_KEY, productIdentifier: productIdentifier)
}


// MARK: - SKReceipt Refresh Request Delegate
func requestDidFinish(_ request: SKRequest) {
DispatchQueue.main.async {
if request is SKReceiptRefreshRequest {
self.validateReceipt()
self.validateAppStoreReceipt()
}
}
}
Expand All @@ -123,16 +124,16 @@ class IAPReceiptService: NSObject, SKRequestDelegate {


/* MARK: - Private methods. */
private func refreshReceipt() {
private func refreshAppStoreReceipt() {
let request = SKReceiptRefreshRequest(receiptProperties: nil)
request.delegate = self
request.start()
}

// Validate App Store receipt using Fovea.Billing validator.
private func validateReceipt() {
private func validateAppStoreReceipt() {
guard let appStoreReceiptURL = Bundle.main.appStoreReceiptURL, FileManager.default.fileExists(atPath: appStoreReceiptURL.path) else {
refreshReceipt() // validateReceipt will be called again after receipt refreshing finishes.
refreshAppStoreReceipt() // validateReceipt will be called again after receipt refreshing finishes.
return
}

Expand Down Expand Up @@ -193,14 +194,14 @@ class IAPReceiptService: NSObject, SKRequestDelegate {
print("[receipt error] Failed to validate the receipt: \(error?.localizedDescription ?? "")")
return
}
self.parseReceipt(json)
self.parseBillingResponse(json)
}
}.resume()
}

// Get user purchases informations from Fovea.Billing validator
// (subscription expiration date, eligibility for introductory price, ...)
private func parseReceipt(_ json : Dictionary<String, Any>) {
private func parseBillingResponse(_ json : Dictionary<String, Any>) {
guard let data = json["data"] as? [String: Any], let collection = data["collection"] as? [[String: Any]] else {
self.notifyFailed(iapErrorCode: .readReceiptFailed)
return
Expand Down

0 comments on commit dc8e1d3

Please sign in to comment.