ViewController.swift 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  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) { result in
  68. NetworkActivityIndicatorManager.networkOperationFinished()
  69. self.showAlert(self.alertForPurchaseResult(result))
  70. }
  71. }
  72. @IBAction func restorePurchases() {
  73. NetworkActivityIndicatorManager.networkOperationStarted()
  74. SwiftyStoreKit.restorePurchases() { results in
  75. NetworkActivityIndicatorManager.networkOperationFinished()
  76. self.showAlert(self.alertForRestorePurchases(results))
  77. }
  78. }
  79. @IBAction func verifyReceipt() {
  80. NetworkActivityIndicatorManager.networkOperationStarted()
  81. SwiftyStoreKit.verifyReceipt() { result in
  82. NetworkActivityIndicatorManager.networkOperationFinished()
  83. self.showAlert(self.alertForVerifyReceipt(result))
  84. if case .error(let error) = result {
  85. if case .noReceiptData = error {
  86. self.refreshReceipt()
  87. }
  88. }
  89. }
  90. }
  91. func verifyPurchase(_ purchase: RegisteredPurchase) {
  92. NetworkActivityIndicatorManager.networkOperationStarted()
  93. SwiftyStoreKit.verifyReceipt() { result in
  94. NetworkActivityIndicatorManager.networkOperationFinished()
  95. switch result {
  96. case .success(let receipt):
  97. let productId = self.AppBundleId + "." + purchase.rawValue
  98. // Specific behaviour for AutoRenewablePurchase
  99. if purchase == .autoRenewablePurchase {
  100. let purchaseResult = SwiftyStoreKit.verifySubscription(
  101. productId: productId,
  102. inReceipt: receipt,
  103. validUntil: Date()
  104. )
  105. self.showAlert(self.alertForVerifySubscription(purchaseResult))
  106. }
  107. else {
  108. let purchaseResult = SwiftyStoreKit.verifyPurchase(
  109. productId: productId,
  110. inReceipt: receipt
  111. )
  112. self.showAlert(self.alertForVerifyPurchase(purchaseResult))
  113. }
  114. case .error(let error):
  115. self.showAlert(self.alertForVerifyReceipt(result))
  116. if case .noReceiptData = error {
  117. self.refreshReceipt()
  118. }
  119. }
  120. }
  121. }
  122. func refreshReceipt() {
  123. SwiftyStoreKit.refreshReceipt { (result) -> () in
  124. self.showAlert(self.alertForRefreshReceipt(result))
  125. }
  126. }
  127. override var preferredStatusBarStyle: UIStatusBarStyle {
  128. return .lightContent
  129. }
  130. }
  131. // MARK: User facing alerts
  132. extension ViewController {
  133. func alertWithTitle(_ title: String, message: String) -> UIAlertController {
  134. let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
  135. alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
  136. return alert
  137. }
  138. func showAlert(_ alert: UIAlertController) {
  139. guard let _ = self.presentedViewController else {
  140. self.present(alert, animated: true, completion: nil)
  141. return
  142. }
  143. }
  144. func alertForProductRetrievalInfo(_ result: SwiftyStoreKit.RetrieveResults) -> UIAlertController {
  145. if let product = result.retrievedProducts.first {
  146. let numberFormatter = NumberFormatter()
  147. numberFormatter.locale = product.priceLocale
  148. numberFormatter.numberStyle = .currency
  149. let priceString = numberFormatter.string(from: product.price)
  150. return alertWithTitle(product.localizedTitle, message: "\(product.localizedDescription) - \(priceString)")
  151. }
  152. else if let invalidProductId = result.invalidProductIDs.first {
  153. return alertWithTitle("Could not retrieve product info", message: "Invalid product identifier: \(invalidProductId)")
  154. }
  155. else {
  156. let errorString = result.error?.localizedDescription ?? "Unknown error. Please contact support"
  157. return alertWithTitle("Could not retrieve product info", message: errorString)
  158. }
  159. }
  160. func alertForPurchaseResult(_ result: SwiftyStoreKit.PurchaseResult) -> UIAlertController {
  161. switch result {
  162. case .success(let productId):
  163. print("Purchase Success: \(productId)")
  164. return alertWithTitle("Thank You", message: "Purchase completed")
  165. case .error(let error):
  166. print("Purchase Failed: \(error)")
  167. switch error {
  168. case .failed(let error):
  169. if (error as NSError).domain == SKErrorDomain {
  170. return alertWithTitle("Purchase failed", message: "Please check your Internet connection or try again later")
  171. }
  172. return alertWithTitle("Purchase failed", message: "Unknown error. Please contact support")
  173. case .invalidProductId(let productId):
  174. return alertWithTitle("Purchase failed", message: "\(productId) is not a valid product identifier")
  175. case .noProductIdentifier:
  176. return alertWithTitle("Purchase failed", message: "Product not found")
  177. case .paymentNotAllowed:
  178. return alertWithTitle("Payments not enabled", message: "You are not allowed to make payments")
  179. }
  180. }
  181. }
  182. func alertForRestorePurchases(_ results: SwiftyStoreKit.RestoreResults) -> UIAlertController {
  183. if results.restoreFailedProducts.count > 0 {
  184. print("Restore Failed: \(results.restoreFailedProducts)")
  185. return alertWithTitle("Restore failed", message: "Unknown error. Please contact support")
  186. }
  187. else if results.restoredProductIds.count > 0 {
  188. print("Restore Success: \(results.restoredProductIds)")
  189. return alertWithTitle("Purchases Restored", message: "All purchases have been restored")
  190. }
  191. else {
  192. print("Nothing to Restore")
  193. return alertWithTitle("Nothing to restore", message: "No previous purchases were found")
  194. }
  195. }
  196. func alertForVerifyReceipt(_ result: SwiftyStoreKit.VerifyReceiptResult) -> UIAlertController {
  197. switch result {
  198. case .success(let receipt):
  199. print("Verify receipt Success: \(receipt)")
  200. return alertWithTitle("Receipt verified", message: "Receipt verified remotly")
  201. case .error(let error):
  202. print("Verify receipt Failed: \(error)")
  203. switch (error) {
  204. case .noReceiptData :
  205. return alertWithTitle("Receipt verification", message: "No receipt data, application will try to get a new one. Try again.")
  206. default:
  207. return alertWithTitle("Receipt verification", message: "Receipt verification failed")
  208. }
  209. }
  210. }
  211. func alertForVerifySubscription(_ result: SwiftyStoreKit.VerifySubscriptionResult) -> UIAlertController {
  212. switch result {
  213. case .purchased(let expiresDate):
  214. print("Product is valid until \(expiresDate)")
  215. return alertWithTitle("Product is purchased", message: "Product is valid until \(expiresDate)")
  216. case .expired(let expiresDate):
  217. print("Product is expired since \(expiresDate)")
  218. return alertWithTitle("Product expired", message: "Product is expired since \(expiresDate)")
  219. case .notPurchased:
  220. print("This product has never been purchased")
  221. return alertWithTitle("Not purchased", message: "This product has never been purchased")
  222. }
  223. }
  224. func alertForVerifyPurchase(_ result: SwiftyStoreKit.VerifyPurchaseResult) -> UIAlertController {
  225. switch result {
  226. case .purchased:
  227. print("Product is purchased")
  228. return alertWithTitle("Product is purchased", message: "Product will not expire")
  229. case .notPurchased:
  230. print("This product has never been purchased")
  231. return alertWithTitle("Not purchased", message: "This product has never been purchased")
  232. }
  233. }
  234. func alertForRefreshReceipt(_ result: SwiftyStoreKit.RefreshReceiptResult) -> UIAlertController {
  235. switch result {
  236. case .success:
  237. print("Receipt refresh Success")
  238. return self.alertWithTitle("Receipt refreshed", message: "Receipt refreshed successfully")
  239. case .error(let error):
  240. print("Receipt refresh Failed: \(error)")
  241. return self.alertWithTitle("Receipt refresh failed", message: "Receipt refresh failed")
  242. }
  243. }
  244. }