passepartout-apple/PassepartoutLibrary/Sources/PassepartoutUtils/Reusable/InApp.swift

224 lines
7.1 KiB
Swift
Raw Normal View History

2022-04-12 13:09:14 +00:00
//
// InApp.swift
// Passepartout
//
// Created by Davide De Rosa on 9/9/19.
2023-03-17 15:56:19 +00:00
// Copyright (c) 2023 Davide De Rosa. All rights reserved.
2022-04-12 13:09:14 +00:00
//
// https://github.com/passepartoutvpn
//
// This file is part of Passepartout.
//
// Passepartout is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Passepartout is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Passepartout. If not, see <http://www.gnu.org/licenses/>.
//
import Foundation
import StoreKit
public enum InAppPurchaseResult {
case done
2023-03-17 20:55:47 +00:00
2022-04-12 13:09:14 +00:00
case cancelled
}
public enum InAppError: Error {
case unknown
}
public class InApp<PID: Hashable & RawRepresentable>: NSObject,
SKProductsRequestDelegate, SKPaymentTransactionObserver
where PID.RawValue == String {
public typealias ProductObserver = ([PID: SKProduct]) -> Void
2023-03-17 20:55:47 +00:00
2022-04-12 13:09:14 +00:00
public typealias TransactionObserver = (Result<InAppPurchaseResult, Error>) -> Void
2023-03-17 20:55:47 +00:00
2022-04-12 13:09:14 +00:00
public typealias RestoreObserver = (Bool, PID?, Error?) -> Void
2023-03-17 20:55:47 +00:00
2022-04-12 13:09:14 +00:00
public typealias FailureObserver = (Error) -> Void
2023-03-17 20:55:47 +00:00
2022-04-12 13:09:14 +00:00
private var productsMap: [PID: SKProduct]
2023-03-17 20:55:47 +00:00
2022-04-12 13:09:14 +00:00
public var products: [SKProduct] {
2022-09-04 18:09:31 +00:00
[SKProduct](productsMap.values)
2022-04-12 13:09:14 +00:00
}
2023-03-17 20:55:47 +00:00
2022-04-12 13:09:14 +00:00
private var productObservers: [ProductObserver]
2023-03-17 20:55:47 +00:00
2022-04-12 13:09:14 +00:00
private var productFailureObserver: FailureObserver?
2023-03-17 20:55:47 +00:00
2022-04-12 13:09:14 +00:00
private var transactionObservers: [String: TransactionObserver]
2023-03-17 20:55:47 +00:00
2022-04-12 13:09:14 +00:00
private var restoreObservers: [RestoreObserver]
2023-03-17 20:55:47 +00:00
2022-04-12 13:09:14 +00:00
public override init() {
productsMap = [:]
productObservers = []
productFailureObserver = nil
transactionObservers = [:]
restoreObservers = []
super.init()
2023-03-17 20:55:47 +00:00
2022-04-12 13:09:14 +00:00
SKPaymentQueue.default().add(self)
}
2023-03-17 20:55:47 +00:00
2022-04-12 13:09:14 +00:00
deinit {
SKPaymentQueue.default().remove(self)
}
2023-03-17 20:55:47 +00:00
2022-04-12 13:09:14 +00:00
public func requestProducts(withIdentifiers identifiers: [PID], completionHandler: ProductObserver?, failureHandler: FailureObserver?) {
let req = SKProductsRequest(productIdentifiers: Set(identifiers.map { $0.rawValue }))
req.delegate = self
if let observer = completionHandler {
productObservers.append(observer)
}
productFailureObserver = failureHandler
req.start()
}
@discardableResult
public func purchase(productWithIdentifier productIdentifier: PID, completionHandler: @escaping TransactionObserver) -> Bool {
guard let product = productsMap[productIdentifier] else {
return false
}
purchase(product: product, completionHandler: completionHandler)
return true
}
public func purchase(product: SKProduct, completionHandler: @escaping TransactionObserver) {
let queue = SKPaymentQueue.default()
let payment = SKPayment(product: product)
transactionObservers[product.productIdentifier] = completionHandler
queue.add(payment)
}
2023-03-17 20:55:47 +00:00
2022-04-12 13:09:14 +00:00
public func restorePurchases(completionHandler: @escaping RestoreObserver) {
let queue = SKPaymentQueue.default()
restoreObservers.append(completionHandler)
queue.restoreCompletedTransactions()
}
2023-03-17 20:55:47 +00:00
2022-04-12 13:09:14 +00:00
public func product(withIdentifier productIdentifier: PID) -> SKProduct? {
2022-09-04 18:09:31 +00:00
productsMap[productIdentifier]
2022-04-12 13:09:14 +00:00
}
// MARK: SKProductsRequestDelegate
public func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) {
DispatchQueue.main.async {
self.receiveProducts(response.products)
}
}
2023-03-17 20:55:47 +00:00
2022-04-12 13:09:14 +00:00
public func request(_ request: SKRequest, didFailWithError error: Error) {
if let _ = request as? SKProductsRequest {
DispatchQueue.main.async {
self.productFailureObserver?(error)
}
}
DispatchQueue.main.async {
self.transactionObservers.removeAll()
}
}
2023-03-17 20:55:47 +00:00
2022-04-12 13:09:14 +00:00
private func receiveProducts(_ products: [SKProduct]) {
productsMap.removeAll()
for p in products {
guard let pid = PID(rawValue: p.productIdentifier) else {
continue
}
productsMap[pid] = p
}
productObservers.forEach { $0(productsMap) }
productObservers.removeAll()
}
// MARK: SKPaymentTransactionObserver
public func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
DispatchQueue.main.async {
let currentRestoreObservers = self.restoreObservers
2023-03-17 20:55:47 +00:00
2022-04-12 13:09:14 +00:00
for tx in transactions {
let productIdentifier = tx.payment.productIdentifier
let observer = self.transactionObservers[productIdentifier]
2023-03-17 20:55:47 +00:00
2022-04-12 13:09:14 +00:00
switch tx.transactionState {
case .purchased:
queue.finishTransaction(tx)
observer?(.success(.done))
case .restored:
queue.finishTransaction(tx)
observer?(.success(.done))
for r in currentRestoreObservers {
guard let pid = PID(rawValue: productIdentifier) else {
continue
}
r(false, pid, nil)
}
2023-03-17 20:55:47 +00:00
2022-04-12 13:09:14 +00:00
case .failed:
queue.finishTransaction(tx)
if let skError = tx.error as? SKError, skError.code == .paymentCancelled {
observer?(.success(.cancelled))
} else {
observer?(.failure(tx.error ?? InAppError.unknown))
for r in currentRestoreObservers {
guard let pid = PID(rawValue: productIdentifier) else {
continue
}
r(false, pid, tx.error)
}
}
2023-03-17 20:55:47 +00:00
2022-04-12 13:09:14 +00:00
default:
break
}
}
}
}
public func paymentQueueRestoreCompletedTransactionsFinished(_ queue: SKPaymentQueue) {
DispatchQueue.main.async {
for r in self.restoreObservers {
r(true, nil, nil)
}
self.restoreObservers.removeAll()
}
}
2023-03-17 20:55:47 +00:00
2022-04-12 13:09:14 +00:00
public func paymentQueue(_ queue: SKPaymentQueue, restoreCompletedTransactionsFailedWithError error: Error) {
DispatchQueue.main.async {
for r in self.restoreObservers {
r(true, nil, error)
}
self.restoreObservers.removeAll()
}
}
}
extension SKProduct {
private var localizedCurrencyFormatter: NumberFormatter {
let fmt = NumberFormatter()
fmt.locale = priceLocale
fmt.numberStyle = .currency
return fmt
}
public var localizedPrice: String? {
2022-09-04 18:09:31 +00:00
localizedCurrencyFormatter.string(from: price)
2022-04-12 13:09:14 +00:00
}
}