ViewController.swift 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  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 = "purchase1"
  29. case purchase2 = "purchase2"
  30. case nonConsumablePurchase = "nonConsumablePurchase"
  31. case consumablePurchase = "consumablePurchase"
  32. case autoRenewablePurchase = "autoRenewablePurchase"
  33. case nonRenewingPurchase = "nonRenewingPurchase"
  34. }
  35. class ViewController: UIViewController {
  36. let AppBundleId = "com.musevisions.iOS.SwiftyStoreKit"
  37. let Purchase1 = RegisteredPurchase.purchase1
  38. let Purchase2 = RegisteredPurchase.autoRenewablePurchase
  39. // MARK: actions
  40. @IBAction func getInfo1() {
  41. getInfo(Purchase1)
  42. }
  43. @IBAction func purchase1() {
  44. purchase(Purchase1)
  45. }
  46. @IBAction func verifyPurchase1() {
  47. verifyPurchase(Purchase1)
  48. }
  49. @IBAction func getInfo2() {
  50. getInfo(Purchase2)
  51. }
  52. @IBAction func purchase2() {
  53. purchase(Purchase2)
  54. }
  55. @IBAction func verifyPurchase2() {
  56. verifyPurchase(Purchase2)
  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 product) = result {
  70. // Deliver content from server, then:
  71. if product.needsFinishTransaction {
  72. SwiftyStoreKit.finishTransaction(product.transaction)
  73. }
  74. }
  75. self.showAlert(self.alertForPurchaseResult(result))
  76. }
  77. }
  78. @IBAction func restorePurchases() {
  79. NetworkActivityIndicatorManager.networkOperationStarted()
  80. SwiftyStoreKit.restorePurchases(atomically: true) { results in
  81. NetworkActivityIndicatorManager.networkOperationFinished()
  82. for product in results.restoredProducts {
  83. // Deliver content from server, then:
  84. if product.needsFinishTransaction {
  85. SwiftyStoreKit.finishTransaction(product.transaction)
  86. }
  87. }
  88. self.showAlert(self.alertForRestorePurchases(results))
  89. }
  90. }
  91. @IBAction func verifyReceipt() {
  92. NetworkActivityIndicatorManager.networkOperationStarted()
  93. let appleValidator = AppleReceiptValidator(service: .production)
  94. SwiftyStoreKit.verifyReceipt(using: appleValidator, password: "your-shared-secret") { result in
  95. NetworkActivityIndicatorManager.networkOperationFinished()
  96. self.showAlert(self.alertForVerifyReceipt(result))
  97. if case .error(let error) = result {
  98. if case .noReceiptData = error {
  99. self.refreshReceipt()
  100. }
  101. }
  102. }
  103. }
  104. func verifyPurchase(_ purchase: RegisteredPurchase) {
  105. NetworkActivityIndicatorManager.networkOperationStarted()
  106. let appleValidator = AppleReceiptValidator(service: .production)
  107. SwiftyStoreKit.verifyReceipt(using: appleValidator, password: "your-shared-secret") { result in
  108. NetworkActivityIndicatorManager.networkOperationFinished()
  109. switch result {
  110. case .success(let receipt):
  111. let productId = self.AppBundleId + "." + purchase.rawValue
  112. // Specific behaviour for AutoRenewablePurchase
  113. if purchase == .autoRenewablePurchase {
  114. let purchaseResult = SwiftyStoreKit.verifySubscription(
  115. productId: productId,
  116. inReceipt: receipt,
  117. validUntil: Date()
  118. )
  119. self.showAlert(self.alertForVerifySubscription(purchaseResult))
  120. }
  121. else {
  122. let purchaseResult = SwiftyStoreKit.verifyPurchase(
  123. productId: productId,
  124. inReceipt: receipt
  125. )
  126. self.showAlert(self.alertForVerifyPurchase(purchaseResult))
  127. }
  128. case .error(let error):
  129. self.showAlert(self.alertForVerifyReceipt(result))
  130. if case .noReceiptData = error {
  131. self.refreshReceipt()
  132. }
  133. }
  134. }
  135. }
  136. func refreshReceipt() {
  137. SwiftyStoreKit.refreshReceipt { result in
  138. self.showAlert(self.alertForRefreshReceipt(result))
  139. }
  140. }
  141. override var preferredStatusBarStyle: UIStatusBarStyle {
  142. return .lightContent
  143. }
  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 let _ = self.presentedViewController 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. }
  163. else if let invalidProductId = result.invalidProductIDs.first {
  164. return alertWithTitle("Could not retrieve product info", message: "Invalid product identifier: \(invalidProductId)")
  165. }
  166. else {
  167. let errorString = result.error?.localizedDescription ?? "Unknown error. Please contact support"
  168. return alertWithTitle("Could not retrieve product info", message: errorString)
  169. }
  170. }
  171. func alertForPurchaseResult(_ result: PurchaseResult) -> UIAlertController {
  172. switch result {
  173. case .success(let product):
  174. print("Purchase Success: \(product.productId)")
  175. return alertWithTitle("Thank You", message: "Purchase completed")
  176. case .error(let error):
  177. print("Purchase Failed: \(error)")
  178. switch error {
  179. case .failed(let error):
  180. if (error as NSError).domain == SKErrorDomain {
  181. return alertWithTitle("Purchase failed", message: "Please check your Internet connection or try again later")
  182. }
  183. return alertWithTitle("Purchase failed", message: "Unknown error. Please contact support")
  184. case .invalidProductId(let productId):
  185. return alertWithTitle("Purchase failed", message: "\(productId) is not a valid product identifier")
  186. case .noProductIdentifier:
  187. return alertWithTitle("Purchase failed", message: "Product not found")
  188. case .paymentNotAllowed:
  189. return alertWithTitle("Payments not enabled", message: "You are not allowed to make payments")
  190. }
  191. }
  192. }
  193. func alertForRestorePurchases(_ results: RestoreResults) -> UIAlertController {
  194. if results.restoreFailedProducts.count > 0 {
  195. print("Restore Failed: \(results.restoreFailedProducts)")
  196. return alertWithTitle("Restore failed", message: "Unknown error. Please contact support")
  197. }
  198. else if results.restoredProducts.count > 0 {
  199. print("Restore Success: \(results.restoredProducts)")
  200. return alertWithTitle("Purchases Restored", message: "All purchases have been restored")
  201. }
  202. else {
  203. print("Nothing to Restore")
  204. return alertWithTitle("Nothing to restore", message: "No previous purchases were found")
  205. }
  206. }
  207. func alertForVerifyReceipt(_ result: VerifyReceiptResult) -> UIAlertController {
  208. switch result {
  209. case .success(let receipt):
  210. print("Verify receipt Success: \(receipt)")
  211. return alertWithTitle("Receipt verified", message: "Receipt verified remotly")
  212. case .error(let error):
  213. print("Verify receipt Failed: \(error)")
  214. switch (error) {
  215. case .noReceiptData :
  216. return alertWithTitle("Receipt verification", message: "No receipt data, application will try to get a new one. Try again.")
  217. default:
  218. return alertWithTitle("Receipt verification", message: "Receipt verification failed")
  219. }
  220. }
  221. }
  222. func alertForVerifySubscription(_ result: VerifySubscriptionResult) -> UIAlertController {
  223. switch result {
  224. case .purchased(let expiresDate):
  225. print("Product is valid until \(expiresDate)")
  226. return alertWithTitle("Product is purchased", message: "Product is valid until \(expiresDate)")
  227. case .expired(let expiresDate):
  228. print("Product is expired since \(expiresDate)")
  229. return alertWithTitle("Product expired", message: "Product is expired since \(expiresDate)")
  230. case .notPurchased:
  231. print("This product has never been purchased")
  232. return alertWithTitle("Not purchased", message: "This product has never been purchased")
  233. }
  234. }
  235. func alertForVerifyPurchase(_ result: VerifyPurchaseResult) -> UIAlertController {
  236. switch result {
  237. case .purchased:
  238. print("Product is purchased")
  239. return alertWithTitle("Product is purchased", message: "Product will not expire")
  240. case .notPurchased:
  241. print("This product has never been purchased")
  242. return alertWithTitle("Not purchased", message: "This product has never been purchased")
  243. }
  244. }
  245. func alertForRefreshReceipt(_ result: RefreshReceiptResult) -> UIAlertController {
  246. switch result {
  247. case .success(let receiptData):
  248. print("Receipt refresh Success: \(receiptData.base64EncodedString)")
  249. return alertWithTitle("Receipt refreshed", message: "Receipt refreshed successfully")
  250. case .error(let error):
  251. print("Receipt refresh Failed: \(error)")
  252. return alertWithTitle("Receipt refresh failed", message: "Receipt refresh failed")
  253. }
  254. }
  255. }