ViewController.swift 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. //
  2. // ViewController.swift
  3. // SwiftyStoreKit-tvOS-Demo
  4. //
  5. // Created by Andrea Bizzotto on 15/03/2017.
  6. // Copyright © 2017 musevisions. All rights reserved.
  7. //
  8. import UIKit
  9. import StoreKit
  10. import SwiftyStoreKit
  11. enum RegisteredPurchase: String {
  12. case purchase1
  13. case purchase2
  14. case nonConsumablePurchase
  15. case consumablePurchase
  16. case autoRenewablePurchase
  17. case nonRenewingPurchase
  18. }
  19. class ViewController: UIViewController {
  20. let appBundleId = "com.musevisions.tvOS.SwiftyStoreKit"
  21. let purchase1Suffix = RegisteredPurchase.purchase1
  22. let purchase2Suffix = RegisteredPurchase.autoRenewablePurchase
  23. // MARK: actions
  24. @IBAction func getInfo1() {
  25. getInfo(purchase1Suffix)
  26. }
  27. @IBAction func purchase1() {
  28. purchase(purchase1Suffix)
  29. }
  30. @IBAction func verifyPurchase1() {
  31. verifyPurchase(purchase1Suffix)
  32. }
  33. @IBAction func getInfo2() {
  34. getInfo(purchase2Suffix)
  35. }
  36. @IBAction func purchase2() {
  37. purchase(purchase2Suffix)
  38. }
  39. @IBAction func verifyPurchase2() {
  40. verifyPurchase(purchase2Suffix)
  41. }
  42. func getInfo(_ purchase: RegisteredPurchase) {
  43. SwiftyStoreKit.retrieveProductsInfo([appBundleId + "." + purchase.rawValue]) { result in
  44. self.showAlert(self.alertForProductRetrievalInfo(result))
  45. }
  46. }
  47. func purchase(_ purchase: RegisteredPurchase) {
  48. SwiftyStoreKit.purchaseProduct(appBundleId + "." + purchase.rawValue, atomically: true) { result in
  49. if case .success(let product) = result {
  50. // Deliver content from server, then:
  51. if product.needsFinishTransaction {
  52. SwiftyStoreKit.finishTransaction(product.transaction)
  53. }
  54. }
  55. if let alert = self.alertForPurchaseResult(result) {
  56. self.showAlert(alert)
  57. }
  58. }
  59. }
  60. @IBAction func restorePurchases() {
  61. SwiftyStoreKit.restorePurchases(atomically: true) { results in
  62. for product in results.restoredProducts {
  63. // Deliver content from server, then:
  64. if product.needsFinishTransaction {
  65. SwiftyStoreKit.finishTransaction(product.transaction)
  66. }
  67. }
  68. self.showAlert(self.alertForRestorePurchases(results))
  69. }
  70. }
  71. @IBAction func verifyReceipt() {
  72. let appleValidator = AppleReceiptValidator(service: .production)
  73. SwiftyStoreKit.verifyReceipt(using: appleValidator, password: "your-shared-secret") { result in
  74. self.showAlert(self.alertForVerifyReceipt(result))
  75. if case .error(let error) = result {
  76. if case .noReceiptData = error {
  77. self.refreshReceipt()
  78. }
  79. }
  80. }
  81. }
  82. func verifyPurchase(_ purchase: RegisteredPurchase) {
  83. let appleValidator = AppleReceiptValidator(service: .production)
  84. SwiftyStoreKit.verifyReceipt(using: appleValidator, password: "your-shared-secret") { result in
  85. switch result {
  86. case .success(let receipt):
  87. let productId = self.appBundleId + "." + purchase.rawValue
  88. switch purchase {
  89. case .autoRenewablePurchase:
  90. let purchaseResult = SwiftyStoreKit.verifySubscription(
  91. type: .autoRenewable,
  92. productId: productId,
  93. inReceipt: receipt,
  94. validUntil: Date()
  95. )
  96. self.showAlert(self.alertForVerifySubscription(purchaseResult))
  97. case .nonRenewingPurchase:
  98. let purchaseResult = SwiftyStoreKit.verifySubscription(
  99. type: .nonRenewing(validDuration: 60),
  100. productId: productId,
  101. inReceipt: receipt,
  102. validUntil: Date()
  103. )
  104. self.showAlert(self.alertForVerifySubscription(purchaseResult))
  105. default:
  106. let purchaseResult = SwiftyStoreKit.verifyPurchase(
  107. productId: productId,
  108. inReceipt: receipt
  109. )
  110. self.showAlert(self.alertForVerifyPurchase(purchaseResult))
  111. }
  112. case .error(let error):
  113. self.showAlert(self.alertForVerifyReceipt(result))
  114. if case .noReceiptData = error {
  115. self.refreshReceipt()
  116. }
  117. }
  118. }
  119. }
  120. func refreshReceipt() {
  121. SwiftyStoreKit.refreshReceipt { result in
  122. self.showAlert(self.alertForRefreshReceipt(result))
  123. }
  124. }
  125. }
  126. // MARK: User facing alerts
  127. extension ViewController {
  128. func alertWithTitle(_ title: String, message: String) -> UIAlertController {
  129. let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
  130. alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
  131. return alert
  132. }
  133. func showAlert(_ alert: UIAlertController) {
  134. guard let _ = self.presentedViewController else {
  135. self.present(alert, animated: true, completion: nil)
  136. return
  137. }
  138. }
  139. func alertForProductRetrievalInfo(_ result: RetrieveResults) -> UIAlertController {
  140. if let product = result.retrievedProducts.first {
  141. let priceString = product.localizedPrice!
  142. return alertWithTitle(product.localizedTitle, message: "\(product.localizedDescription) - \(priceString)")
  143. } else if let invalidProductId = result.invalidProductIDs.first {
  144. return alertWithTitle("Could not retrieve product info", message: "Invalid product identifier: \(invalidProductId)")
  145. } else {
  146. let errorString = result.error?.localizedDescription ?? "Unknown error. Please contact support"
  147. return alertWithTitle("Could not retrieve product info", message: errorString)
  148. }
  149. }
  150. func alertForPurchaseResult(_ result: PurchaseResult) -> UIAlertController? {
  151. switch result {
  152. case .success(let product):
  153. print("Purchase Success: \(product.productId)")
  154. return alertWithTitle("Thank You", message: "Purchase completed")
  155. case .error(let error):
  156. print("Purchase Failed: \(error)")
  157. switch error.code {
  158. case .unknown: return alertWithTitle("Purchase failed", message: "Unknown error. Please contact support")
  159. case .clientInvalid: // client is not allowed to issue the request, etc.
  160. return alertWithTitle("Purchase failed", message: "Not allowed to make the payment")
  161. case .paymentCancelled: // user cancelled the request, etc.
  162. return nil
  163. case .paymentInvalid: // purchase identifier was invalid, etc.
  164. return alertWithTitle("Purchase failed", message: "The purchase identifier was invalid")
  165. case .paymentNotAllowed: // this device is not allowed to make the payment
  166. return alertWithTitle("Purchase failed", message: "The device is not allowed to make the payment")
  167. case .storeProductNotAvailable: // Product is not available in the current storefront
  168. return alertWithTitle("Purchase failed", message: "The product is not available in the current storefront")
  169. case .cloudServicePermissionDenied: // user has not allowed access to cloud service information
  170. return alertWithTitle("Purchase failed", message: "Access to cloud service information is not allowed")
  171. case .cloudServiceNetworkConnectionFailed: // the device could not connect to the nework
  172. return alertWithTitle("Purchase failed", message: "Could not connect to the network")
  173. }
  174. }
  175. }
  176. func alertForRestorePurchases(_ results: RestoreResults) -> UIAlertController {
  177. if results.restoreFailedProducts.count > 0 {
  178. print("Restore Failed: \(results.restoreFailedProducts)")
  179. return alertWithTitle("Restore failed", message: "Unknown error. Please contact support")
  180. } else if results.restoredProducts.count > 0 {
  181. print("Restore Success: \(results.restoredProducts)")
  182. return alertWithTitle("Purchases Restored", message: "All purchases have been restored")
  183. } else {
  184. print("Nothing to Restore")
  185. return alertWithTitle("Nothing to restore", message: "No previous purchases were found")
  186. }
  187. }
  188. func alertForVerifyReceipt(_ result: VerifyReceiptResult) -> UIAlertController {
  189. switch result {
  190. case .success(let receipt):
  191. print("Verify receipt Success: \(receipt)")
  192. return alertWithTitle("Receipt verified", message: "Receipt verified remotly")
  193. case .error(let error):
  194. print("Verify receipt Failed: \(error)")
  195. switch error {
  196. case .noReceiptData :
  197. return alertWithTitle("Receipt verification", message: "No receipt data, application will try to get a new one. Try again.")
  198. default:
  199. return alertWithTitle("Receipt verification", message: "Receipt verification failed")
  200. }
  201. }
  202. }
  203. func alertForVerifySubscription(_ result: VerifySubscriptionResult) -> UIAlertController {
  204. switch result {
  205. case .purchased(let expiresDate):
  206. print("Product is valid until \(expiresDate)")
  207. return alertWithTitle("Product is purchased", message: "Product is valid until \(expiresDate)")
  208. case .expired(let expiresDate):
  209. print("Product is expired since \(expiresDate)")
  210. return alertWithTitle("Product expired", message: "Product is expired since \(expiresDate)")
  211. case .notPurchased:
  212. print("This product has never been purchased")
  213. return alertWithTitle("Not purchased", message: "This product has never been purchased")
  214. }
  215. }
  216. func alertForVerifyPurchase(_ result: VerifyPurchaseResult) -> UIAlertController {
  217. switch result {
  218. case .purchased:
  219. print("Product is purchased")
  220. return alertWithTitle("Product is purchased", message: "Product will not expire")
  221. case .notPurchased:
  222. print("This product has never been purchased")
  223. return alertWithTitle("Not purchased", message: "This product has never been purchased")
  224. }
  225. }
  226. func alertForRefreshReceipt(_ result: RefreshReceiptResult) -> UIAlertController {
  227. switch result {
  228. case .success(let receiptData):
  229. print("Receipt refresh Success: \(receiptData.base64EncodedString)")
  230. return alertWithTitle("Receipt refreshed", message: "Receipt refreshed successfully")
  231. case .error(let error):
  232. print("Receipt refresh Failed: \(error)")
  233. return alertWithTitle("Receipt refresh failed", message: "Receipt refresh failed")
  234. }
  235. }
  236. }