ViewController.swift 14 KB

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