|
| 1 | +#if !PMKCocoaPods |
| 2 | +import PromiseKit |
| 3 | +#endif |
| 4 | +import StoreKit |
| 5 | + |
| 6 | +extension SKPaymentQueue { |
| 7 | + public func restoreCompletedTransactions(_: PMKNamespacer) -> Promise<[SKPaymentTransaction]> { |
| 8 | + return PaymentObserver(self).promise |
| 9 | + } |
| 10 | + |
| 11 | + public func restoreCompletedTransactions(_: PMKNamespacer, withApplicationUsername username: String?) -> Promise<[SKPaymentTransaction]> { |
| 12 | + return PaymentObserver(self, withApplicationUsername: true, userName: username).promise |
| 13 | + } |
| 14 | +} |
| 15 | + |
| 16 | +private class PaymentObserver: NSObject, SKPaymentTransactionObserver { |
| 17 | + let (promise, seal) = Promise<[SKPaymentTransaction]>.pending() |
| 18 | + var retainCycle: PaymentObserver? |
| 19 | + var transactions = [SKPaymentTransaction]() |
| 20 | + |
| 21 | + init(_ paymentQueue: SKPaymentQueue, withApplicationUsername: Bool = false, userName: String? = nil) { |
| 22 | + super.init() |
| 23 | + paymentQueue.add(self) |
| 24 | + withApplicationUsername ? |
| 25 | + paymentQueue.restoreCompletedTransactions() : |
| 26 | + paymentQueue.restoreCompletedTransactions(withApplicationUsername: userName) |
| 27 | + retainCycle = self |
| 28 | + } |
| 29 | + |
| 30 | + func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) { |
| 31 | + self.transactions += transactions.filter { $0.transactionState == .restored } |
| 32 | + transactions.forEach(queue.finishTransaction) |
| 33 | + } |
| 34 | + |
| 35 | + func paymentQueueRestoreCompletedTransactionsFinished(_ queue: SKPaymentQueue) { |
| 36 | + finish(queue) |
| 37 | + } |
| 38 | + |
| 39 | + func paymentQueue(_ queue: SKPaymentQueue, restoreCompletedTransactionsFailedWithError error: Error) { |
| 40 | + finish(queue, with: error) |
| 41 | + } |
| 42 | + |
| 43 | + func finish(_ queue: SKPaymentQueue, with error: Error? = nil) { |
| 44 | + if let error = error { |
| 45 | + seal.reject(error) |
| 46 | + } else { |
| 47 | + seal.fulfill(transactions) |
| 48 | + } |
| 49 | + |
| 50 | + queue.remove(self) |
| 51 | + retainCycle = nil |
| 52 | + } |
| 53 | +} |
0 commit comments