ViewController.swift 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  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 nonRenewingPurchase
  33. case autoRenewableWeekly
  34. case autoRenewableMonthly
  35. case autoRenewableYearly
  36. }
  37. class ViewController: UIViewController {
  38. let appBundleId = "com.musevisions.iOS.SwiftyStoreKit"
  39. // MARK: non consumable
  40. @IBOutlet var nonConsumableAtomicSwitch: UISwitch!
  41. @IBAction func nonConsumableGetInfo() {
  42. getInfo(.nonConsumablePurchase)
  43. }
  44. @IBAction func nonConsumablePurchase() {
  45. purchase(.nonConsumablePurchase, atomically: nonConsumableAtomicSwitch.isOn)
  46. }
  47. @IBAction func nonConsumableVerifyPurchase() {
  48. verifyPurchase(.nonConsumablePurchase)
  49. }
  50. // MARK: consumable
  51. @IBOutlet var consumableAtomicSwitch: UISwitch!
  52. @IBAction func consumableGetInfo() {
  53. getInfo(.consumablePurchase)
  54. }
  55. @IBAction func consumablePurchase() {
  56. purchase(.consumablePurchase, atomically: consumableAtomicSwitch.isOn)
  57. }
  58. @IBAction func consumableVerifyPurchase() {
  59. verifyPurchase(.consumablePurchase)
  60. }
  61. // MARK: non renewing
  62. @IBOutlet var nonRenewingAtomicSwitch: UISwitch!
  63. @IBAction func nonRenewingGetInfo() {
  64. getInfo(.nonRenewingPurchase)
  65. }
  66. @IBAction func nonRenewingPurchase() {
  67. purchase(.nonRenewingPurchase, atomically: nonRenewingAtomicSwitch.isOn)
  68. }
  69. @IBAction func nonRenewingVerifyPurchase() {
  70. verifyPurchase(.nonRenewingPurchase)
  71. }
  72. // MARK: auto renewable
  73. @IBOutlet var autoRenewableAtomicSwitch: UISwitch!
  74. @IBOutlet var autoRenewableSubscriptionSegmentedControl: UISegmentedControl!
  75. var autoRenewableSubscription: RegisteredPurchase {
  76. switch autoRenewableSubscriptionSegmentedControl.selectedSegmentIndex {
  77. case 0: return .autoRenewableWeekly
  78. case 1: return .autoRenewableMonthly
  79. case 2: return .autoRenewableYearly
  80. default: return .autoRenewableWeekly
  81. }
  82. }
  83. @IBAction func autoRenewableGetInfo() {
  84. getInfo(autoRenewableSubscription)
  85. }
  86. @IBAction func autoRenewablePurchase() {
  87. purchase(autoRenewableSubscription, atomically: autoRenewableAtomicSwitch.isOn)
  88. }
  89. @IBAction func autoRenewableVerifyPurchase() {
  90. verifyPurchase(autoRenewableSubscription)
  91. }
  92. func getInfo(_ purchase: RegisteredPurchase) {
  93. NetworkActivityIndicatorManager.networkOperationStarted()
  94. SwiftyStoreKit.retrieveProductsInfo([appBundleId + "." + purchase.rawValue]) { result in
  95. NetworkActivityIndicatorManager.networkOperationFinished()
  96. self.showAlert(self.alertForProductRetrievalInfo(result))
  97. }
  98. }
  99. func purchase(_ purchase: RegisteredPurchase, atomically: Bool) {
  100. NetworkActivityIndicatorManager.networkOperationStarted()
  101. SwiftyStoreKit.purchaseProduct(appBundleId + "." + purchase.rawValue, atomically: atomically) { result in
  102. NetworkActivityIndicatorManager.networkOperationFinished()
  103. if case .success(let purchase) = result {
  104. // Deliver content from server, then:
  105. if purchase.needsFinishTransaction {
  106. SwiftyStoreKit.finishTransaction(purchase.transaction)
  107. }
  108. }
  109. if let alert = self.alertForPurchaseResult(result) {
  110. self.showAlert(alert)
  111. }
  112. }
  113. }
  114. @IBAction func restorePurchases() {
  115. NetworkActivityIndicatorManager.networkOperationStarted()
  116. SwiftyStoreKit.restorePurchases(atomically: true) { results in
  117. NetworkActivityIndicatorManager.networkOperationFinished()
  118. for purchase in results.restoredPurchases where purchase.needsFinishTransaction {
  119. // Deliver content from server, then:
  120. SwiftyStoreKit.finishTransaction(purchase.transaction)
  121. }
  122. self.showAlert(self.alertForRestorePurchases(results))
  123. }
  124. }
  125. @IBAction func verifyReceipt() {
  126. NetworkActivityIndicatorManager.networkOperationStarted()
  127. verifyReceipt { result in
  128. NetworkActivityIndicatorManager.networkOperationFinished()
  129. self.showAlert(self.alertForVerifyReceipt(result))
  130. }
  131. }
  132. func verifyReceipt(completion: @escaping (VerifyReceiptResult) -> Void) {
  133. let appleValidator = AppleReceiptValidator(service: .production, sharedSecret: "your-shared-secret")
  134. SwiftyStoreKit.verifyReceipt(using: appleValidator, completion: completion)
  135. }
  136. func verifyPurchase(_ purchase: RegisteredPurchase) {
  137. NetworkActivityIndicatorManager.networkOperationStarted()
  138. verifyReceipt { result in
  139. NetworkActivityIndicatorManager.networkOperationFinished()
  140. switch result {
  141. case .success(let receipt):
  142. let productId = self.appBundleId + "." + purchase.rawValue
  143. switch purchase {
  144. case .autoRenewableWeekly, .autoRenewableMonthly, .autoRenewableYearly:
  145. let purchaseResult = SwiftyStoreKit.verifySubscription(
  146. type: .autoRenewable,
  147. productId: productId,
  148. inReceipt: receipt,
  149. validUntil: Date()
  150. )
  151. self.showAlert(self.alertForVerifySubscription(purchaseResult))
  152. case .nonRenewingPurchase:
  153. let purchaseResult = SwiftyStoreKit.verifySubscription(
  154. type: .nonRenewing(validDuration: 60),
  155. productId: productId,
  156. inReceipt: receipt,
  157. validUntil: Date()
  158. )
  159. self.showAlert(self.alertForVerifySubscription(purchaseResult))
  160. default:
  161. let purchaseResult = SwiftyStoreKit.verifyPurchase(
  162. productId: productId,
  163. inReceipt: receipt
  164. )
  165. self.showAlert(self.alertForVerifyPurchase(purchaseResult))
  166. }
  167. case .error:
  168. self.showAlert(self.alertForVerifyReceipt(result))
  169. }
  170. }
  171. }
  172. #if os(iOS)
  173. override var preferredStatusBarStyle: UIStatusBarStyle {
  174. return .lightContent
  175. }
  176. #endif
  177. }
  178. // MARK: User facing alerts
  179. extension ViewController {
  180. func alertWithTitle(_ title: String, message: String) -> UIAlertController {
  181. let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
  182. alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
  183. return alert
  184. }
  185. func showAlert(_ alert: UIAlertController) {
  186. guard self.presentedViewController != nil else {
  187. self.present(alert, animated: true, completion: nil)
  188. return
  189. }
  190. }
  191. func alertForProductRetrievalInfo(_ result: RetrieveResults) -> UIAlertController {
  192. if let product = result.retrievedProducts.first {
  193. let priceString = product.localizedPrice!
  194. return alertWithTitle(product.localizedTitle, message: "\(product.localizedDescription) - \(priceString)")
  195. } else if let invalidProductId = result.invalidProductIDs.first {
  196. return alertWithTitle("Could not retrieve product info", message: "Invalid product identifier: \(invalidProductId)")
  197. } else {
  198. let errorString = result.error?.localizedDescription ?? "Unknown error. Please contact support"
  199. return alertWithTitle("Could not retrieve product info", message: errorString)
  200. }
  201. }
  202. // swiftlint:disable cyclomatic_complexity
  203. func alertForPurchaseResult(_ result: PurchaseResult) -> UIAlertController? {
  204. switch result {
  205. case .success(let purchase):
  206. print("Purchase Success: \(purchase.productId)")
  207. return alertWithTitle("Thank You", message: "Purchase completed")
  208. case .error(let error):
  209. print("Purchase Failed: \(error)")
  210. switch error.code {
  211. case .unknown: return alertWithTitle("Purchase failed", message: error.localizedDescription)
  212. case .clientInvalid: // client is not allowed to issue the request, etc.
  213. return alertWithTitle("Purchase failed", message: "Not allowed to make the payment")
  214. case .paymentCancelled: // user cancelled the request, etc.
  215. return nil
  216. case .paymentInvalid: // purchase identifier was invalid, etc.
  217. return alertWithTitle("Purchase failed", message: "The purchase identifier was invalid")
  218. case .paymentNotAllowed: // this device is not allowed to make the payment
  219. return alertWithTitle("Purchase failed", message: "The device is not allowed to make the payment")
  220. case .storeProductNotAvailable: // Product is not available in the current storefront
  221. return alertWithTitle("Purchase failed", message: "The product is not available in the current storefront")
  222. case .cloudServicePermissionDenied: // user has not allowed access to cloud service information
  223. return alertWithTitle("Purchase failed", message: "Access to cloud service information is not allowed")
  224. case .cloudServiceNetworkConnectionFailed: // the device could not connect to the nework
  225. return alertWithTitle("Purchase failed", message: "Could not connect to the network")
  226. case .cloudServiceRevoked: // user has revoked permission to use this cloud service
  227. return alertWithTitle("Purchase failed", message: "Cloud service was revoked")
  228. }
  229. }
  230. }
  231. func alertForRestorePurchases(_ results: RestoreResults) -> UIAlertController {
  232. if results.restoreFailedPurchases.count > 0 {
  233. print("Restore Failed: \(results.restoreFailedPurchases)")
  234. return alertWithTitle("Restore failed", message: "Unknown error. Please contact support")
  235. } else if results.restoredPurchases.count > 0 {
  236. print("Restore Success: \(results.restoredPurchases)")
  237. return alertWithTitle("Purchases Restored", message: "All purchases have been restored")
  238. } else {
  239. print("Nothing to Restore")
  240. return alertWithTitle("Nothing to restore", message: "No previous purchases were found")
  241. }
  242. }
  243. func alertForVerifyReceipt(_ result: VerifyReceiptResult) -> UIAlertController {
  244. switch result {
  245. case .success(let receipt):
  246. print("Verify receipt Success: \(receipt)")
  247. return alertWithTitle("Receipt verified", message: "Receipt verified remotely")
  248. case .error(let error):
  249. print("Verify receipt Failed: \(error)")
  250. switch error {
  251. case .noReceiptData:
  252. return alertWithTitle("Receipt verification", message: "No receipt data. Try again.")
  253. case .networkError(let error):
  254. return alertWithTitle("Receipt verification", message: "Network error while verifying receipt: \(error)")
  255. default:
  256. return alertWithTitle("Receipt verification", message: "Receipt verification failed: \(error)")
  257. }
  258. }
  259. }
  260. func alertForVerifySubscription(_ result: VerifySubscriptionResult) -> UIAlertController {
  261. switch result {
  262. case .purchased(let expiryDate):
  263. print("Product is valid until \(expiryDate)")
  264. return alertWithTitle("Product is purchased", message: "Product is valid until \(expiryDate)")
  265. case .expired(let expiryDate):
  266. print("Product is expired since \(expiryDate)")
  267. return alertWithTitle("Product expired", message: "Product is expired since \(expiryDate)")
  268. case .notPurchased:
  269. print("This product has never been purchased")
  270. return alertWithTitle("Not purchased", message: "This product has never been purchased")
  271. }
  272. }
  273. func alertForVerifyPurchase(_ result: VerifyPurchaseResult) -> UIAlertController {
  274. switch result {
  275. case .purchased:
  276. print("Product is purchased")
  277. return alertWithTitle("Product is purchased", message: "Product will not expire")
  278. case .notPurchased:
  279. print("This product has never been purchased")
  280. return alertWithTitle("Not purchased", message: "This product has never been purchased")
  281. }
  282. }
  283. }