ViewController.swift 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. //
  2. // ViewController.swift
  3. // SwiftyStoreKit
  4. //
  5. // Created by Andrea Bizzotto on 03/09/2015.
  6. //
  7. // Permission is hereby granted, free of charge, to any person obtaining a copy
  8. // of this software and associated documentation files (the "Software"), to deal
  9. // in the Software without restriction, including without limitation the rights
  10. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11. // copies of the Software, and to permit persons to whom the Software is
  12. // furnished to do so, subject to the following conditions:
  13. //
  14. // The above copyright notice and this permission notice shall be included in
  15. // all copies or substantial portions of the Software.
  16. //
  17. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  19. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  20. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  21. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  22. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  23. // THE SOFTWARE.
  24. import UIKit
  25. import StoreKit
  26. import SwiftyStoreKit
  27. enum RegisteredPurchase: String {
  28. case purchase1
  29. case purchase2
  30. case nonConsumablePurchase
  31. case consumablePurchase
  32. case autoRenewablePurchase
  33. case nonRenewingPurchase
  34. }
  35. class ViewController: UIViewController {
  36. let appBundleId = "com.musevisions.iOS.SwiftyStoreKit"
  37. let purchase1Suffix = RegisteredPurchase.purchase1
  38. let purchase2Suffix = RegisteredPurchase.autoRenewablePurchase
  39. // MARK: actions
  40. @IBAction func getInfo1() {
  41. getInfo(purchase1Suffix)
  42. }
  43. @IBAction func purchase1() {
  44. purchase(purchase1Suffix)
  45. }
  46. @IBAction func verifyPurchase1() {
  47. verifyPurchase(purchase1Suffix)
  48. }
  49. @IBAction func getInfo2() {
  50. getInfo(purchase2Suffix)
  51. }
  52. @IBAction func purchase2() {
  53. purchase(purchase2Suffix)
  54. }
  55. @IBAction func verifyPurchase2() {
  56. verifyPurchase(purchase2Suffix)
  57. }
  58. func getInfo(_ purchase: RegisteredPurchase) {
  59. NetworkActivityIndicatorManager.networkOperationStarted()
  60. SwiftyStoreKit.retrieveProductsInfo([appBundleId + "." + purchase.rawValue]) { result in
  61. NetworkActivityIndicatorManager.networkOperationFinished()
  62. self.showAlert(self.alertForProductRetrievalInfo(result))
  63. }
  64. }
  65. func purchase(_ purchase: RegisteredPurchase) {
  66. NetworkActivityIndicatorManager.networkOperationStarted()
  67. SwiftyStoreKit.purchaseProduct(appBundleId + "." + purchase.rawValue, atomically: true) { result in
  68. NetworkActivityIndicatorManager.networkOperationFinished()
  69. if case .success(let purchase) = result {
  70. // Deliver content from server, then:
  71. if purchase.needsFinishTransaction {
  72. SwiftyStoreKit.finishTransaction(purchase.transaction)
  73. }
  74. }
  75. if let alert = self.alertForPurchaseResult(result) {
  76. self.showAlert(alert)
  77. }
  78. }
  79. }
  80. @IBAction func restorePurchases() {
  81. NetworkActivityIndicatorManager.networkOperationStarted()
  82. SwiftyStoreKit.restorePurchases(atomically: true) { results in
  83. NetworkActivityIndicatorManager.networkOperationFinished()
  84. for purchase in results.restoredPurchases where purchase.needsFinishTransaction {
  85. // Deliver content from server, then:
  86. SwiftyStoreKit.finishTransaction(purchase.transaction)
  87. }
  88. self.showAlert(self.alertForRestorePurchases(results))
  89. }
  90. }
  91. @IBAction func verifyReceipt() {
  92. NetworkActivityIndicatorManager.networkOperationStarted()
  93. verifyReceipt { result in
  94. NetworkActivityIndicatorManager.networkOperationFinished()
  95. self.showAlert(self.alertForVerifyReceipt(result))
  96. }
  97. }
  98. func verifyReceipt(completion: @escaping (VerifyReceiptResult) -> Void) {
  99. let appleValidator = AppleReceiptValidator(service: .production)
  100. let password = "your-shared-secret"
  101. SwiftyStoreKit.verifyReceipt(using: appleValidator, password: password, completion: completion)
  102. }
  103. func verifyPurchase(_ purchase: RegisteredPurchase) {
  104. NetworkActivityIndicatorManager.networkOperationStarted()
  105. verifyReceipt { result in
  106. NetworkActivityIndicatorManager.networkOperationFinished()
  107. switch result {
  108. case .success(let receipt):
  109. let productId = self.appBundleId + "." + purchase.rawValue
  110. switch purchase {
  111. case .autoRenewablePurchase:
  112. let purchaseResult = SwiftyStoreKit.verifySubscription(
  113. type: .autoRenewable,
  114. productId: productId,
  115. inReceipt: receipt,
  116. validUntil: Date()
  117. )
  118. self.showAlert(self.alertForVerifySubscription(purchaseResult))
  119. case .nonRenewingPurchase:
  120. let purchaseResult = SwiftyStoreKit.verifySubscription(
  121. type: .nonRenewing(validDuration: 60),
  122. productId: productId,
  123. inReceipt: receipt,
  124. validUntil: Date()
  125. )
  126. self.showAlert(self.alertForVerifySubscription(purchaseResult))
  127. default:
  128. let purchaseResult = SwiftyStoreKit.verifyPurchase(
  129. productId: productId,
  130. inReceipt: receipt
  131. )
  132. self.showAlert(self.alertForVerifyPurchase(purchaseResult))
  133. }
  134. case .error:
  135. self.showAlert(self.alertForVerifyReceipt(result))
  136. }
  137. }
  138. }
  139. #if os(iOS)
  140. override var preferredStatusBarStyle: UIStatusBarStyle {
  141. return .lightContent
  142. }
  143. #endif
  144. }
  145. // MARK: User facing alerts
  146. extension ViewController {
  147. func alertWithTitle(_ title: String, message: String) -> UIAlertController {
  148. let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
  149. alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
  150. return alert
  151. }
  152. func showAlert(_ alert: UIAlertController) {
  153. guard self.presentedViewController != nil else {
  154. self.present(alert, animated: true, completion: nil)
  155. return
  156. }
  157. }
  158. func alertForProductRetrievalInfo(_ result: RetrieveResults) -> UIAlertController {
  159. if let product = result.retrievedProducts.first {
  160. let priceString = product.localizedPrice!
  161. return alertWithTitle(product.localizedTitle, message: "\(product.localizedDescription) - \(priceString)")
  162. } else if let invalidProductId = result.invalidProductIDs.first {
  163. return alertWithTitle("Could not retrieve product info", message: "Invalid product identifier: \(invalidProductId)")
  164. } else {
  165. let errorString = result.error?.localizedDescription ?? "Unknown error. Please contact support"
  166. return alertWithTitle("Could not retrieve product info", message: errorString)
  167. }
  168. }
  169. // swiftlint:disable cyclomatic_complexity
  170. func alertForPurchaseResult(_ result: PurchaseResult) -> UIAlertController? {
  171. switch result {
  172. case .success(let purchase):
  173. print("Purchase Success: \(purchase.productId)")
  174. return alertWithTitle("Thank You", message: "Purchase completed")
  175. case .error(let error):
  176. print("Purchase Failed: \(error)")
  177. switch error.code {
  178. case .unknown: return alertWithTitle("Purchase failed", message: "Unknown error. Please contact support")
  179. case .clientInvalid: // client is not allowed to issue the request, etc.
  180. return alertWithTitle("Purchase failed", message: "Not allowed to make the payment")
  181. case .paymentCancelled: // user cancelled the request, etc.
  182. return nil
  183. case .paymentInvalid: // purchase identifier was invalid, etc.
  184. return alertWithTitle("Purchase failed", message: "The purchase identifier was invalid")
  185. case .paymentNotAllowed: // this device is not allowed to make the payment
  186. return alertWithTitle("Purchase failed", message: "The device is not allowed to make the payment")
  187. case .storeProductNotAvailable: // Product is not available in the current storefront
  188. return alertWithTitle("Purchase failed", message: "The product is not available in the current storefront")
  189. case .cloudServicePermissionDenied: // user has not allowed access to cloud service information
  190. return alertWithTitle("Purchase failed", message: "Access to cloud service information is not allowed")
  191. case .cloudServiceNetworkConnectionFailed: // the device could not connect to the nework
  192. return alertWithTitle("Purchase failed", message: "Could not connect to the network")
  193. case .cloudServiceRevoked: // user has revoked permission to use this cloud service
  194. return alertWithTitle("Purchase failed", message: "Cloud service was revoked")
  195. }
  196. }
  197. }
  198. func alertForRestorePurchases(_ results: RestoreResults) -> UIAlertController {
  199. if results.restoreFailedPurchases.count > 0 {
  200. print("Restore Failed: \(results.restoreFailedPurchases)")
  201. return alertWithTitle("Restore failed", message: "Unknown error. Please contact support")
  202. } else if results.restoredPurchases.count > 0 {
  203. print("Restore Success: \(results.restoredPurchases)")
  204. return alertWithTitle("Purchases Restored", message: "All purchases have been restored")
  205. } else {
  206. print("Nothing to Restore")
  207. return alertWithTitle("Nothing to restore", message: "No previous purchases were found")
  208. }
  209. }
  210. func alertForVerifyReceipt(_ result: VerifyReceiptResult) -> UIAlertController {
  211. switch result {
  212. case .success(let receipt):
  213. print("Verify receipt Success: \(receipt)")
  214. return alertWithTitle("Receipt verified", message: "Receipt verified remotely")
  215. case .error(let error):
  216. print("Verify receipt Failed: \(error)")
  217. switch error {
  218. case .noReceiptData:
  219. return alertWithTitle("Receipt verification", message: "No receipt data, application will try to get a new one. Try again.")
  220. case .networkError(let error):
  221. return alertWithTitle("Receipt verification", message: "Network error while verifying receipt: \(error)")
  222. default:
  223. return alertWithTitle("Receipt verification", message: "Receipt verification failed: \(error)")
  224. }
  225. }
  226. }
  227. func alertForVerifySubscription(_ result: VerifySubscriptionResult) -> UIAlertController {
  228. switch result {
  229. case .purchased(let expiryDate):
  230. print("Product is valid until \(expiryDate)")
  231. return alertWithTitle("Product is purchased", message: "Product is valid until \(expiryDate)")
  232. case .expired(let expiryDate):
  233. print("Product is expired since \(expiryDate)")
  234. return alertWithTitle("Product expired", message: "Product is expired since \(expiryDate)")
  235. case .notPurchased:
  236. print("This product has never been purchased")
  237. return alertWithTitle("Not purchased", message: "This product has never been purchased")
  238. }
  239. }
  240. func alertForVerifyPurchase(_ result: VerifyPurchaseResult) -> UIAlertController {
  241. switch result {
  242. case .purchased:
  243. print("Product is purchased")
  244. return alertWithTitle("Product is purchased", message: "Product will not expire")
  245. case .notPurchased:
  246. print("This product has never been purchased")
  247. return alertWithTitle("Not purchased", message: "This product has never been purchased")
  248. }
  249. }
  250. }