ViewController.swift 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  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 product) = result {
  70. // Deliver content from server, then:
  71. if product.needsFinishTransaction {
  72. SwiftyStoreKit.finishTransaction(product.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 product in results.restoredProducts {
  85. // Deliver content from server, then:
  86. if product.needsFinishTransaction {
  87. SwiftyStoreKit.finishTransaction(product.transaction)
  88. }
  89. }
  90. self.showAlert(self.alertForRestorePurchases(results))
  91. }
  92. }
  93. @IBAction func verifyReceipt() {
  94. NetworkActivityIndicatorManager.networkOperationStarted()
  95. let appleValidator = AppleReceiptValidator(service: .production)
  96. SwiftyStoreKit.verifyReceipt(using: appleValidator, password: "your-shared-secret") { result in
  97. NetworkActivityIndicatorManager.networkOperationFinished()
  98. self.showAlert(self.alertForVerifyReceipt(result))
  99. if case .error(let error) = result {
  100. if case .noReceiptData = error {
  101. self.refreshReceipt()
  102. }
  103. }
  104. }
  105. }
  106. func verifyPurchase(_ purchase: RegisteredPurchase) {
  107. NetworkActivityIndicatorManager.networkOperationStarted()
  108. let appleValidator = AppleReceiptValidator(service: .production)
  109. SwiftyStoreKit.verifyReceipt(using: appleValidator, password: "your-shared-secret") { result in
  110. NetworkActivityIndicatorManager.networkOperationFinished()
  111. switch result {
  112. case .success(let receipt):
  113. let productId = self.appBundleId + "." + purchase.rawValue
  114. switch purchase {
  115. case .autoRenewablePurchase:
  116. let purchaseResult = SwiftyStoreKit.verifySubscription(
  117. type: .autoRenewable,
  118. productId: productId,
  119. inReceipt: receipt,
  120. validUntil: Date()
  121. )
  122. self.showAlert(self.alertForVerifySubscription(purchaseResult))
  123. case .nonRenewingPurchase:
  124. let purchaseResult = SwiftyStoreKit.verifySubscription(
  125. type: .nonRenewing(validDuration: 60),
  126. productId: productId,
  127. inReceipt: receipt,
  128. validUntil: Date()
  129. )
  130. self.showAlert(self.alertForVerifySubscription(purchaseResult))
  131. default:
  132. let purchaseResult = SwiftyStoreKit.verifyPurchase(
  133. productId: productId,
  134. inReceipt: receipt
  135. )
  136. self.showAlert(self.alertForVerifyPurchase(purchaseResult))
  137. }
  138. case .error(let error):
  139. self.showAlert(self.alertForVerifyReceipt(result))
  140. if case .noReceiptData = error {
  141. self.refreshReceipt()
  142. }
  143. }
  144. }
  145. }
  146. func refreshReceipt() {
  147. SwiftyStoreKit.refreshReceipt { result in
  148. self.showAlert(self.alertForRefreshReceipt(result))
  149. }
  150. }
  151. override var preferredStatusBarStyle: UIStatusBarStyle {
  152. return .lightContent
  153. }
  154. }
  155. // MARK: User facing alerts
  156. extension ViewController {
  157. func alertWithTitle(_ title: String, message: String) -> UIAlertController {
  158. let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
  159. alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
  160. return alert
  161. }
  162. func showAlert(_ alert: UIAlertController) {
  163. guard let _ = self.presentedViewController else {
  164. self.present(alert, animated: true, completion: nil)
  165. return
  166. }
  167. }
  168. func alertForProductRetrievalInfo(_ result: RetrieveResults) -> UIAlertController {
  169. if let product = result.retrievedProducts.first {
  170. let priceString = product.localizedPrice!
  171. return alertWithTitle(product.localizedTitle, message: "\(product.localizedDescription) - \(priceString)")
  172. } else if let invalidProductId = result.invalidProductIDs.first {
  173. return alertWithTitle("Could not retrieve product info", message: "Invalid product identifier: \(invalidProductId)")
  174. } else {
  175. let errorString = result.error?.localizedDescription ?? "Unknown error. Please contact support"
  176. return alertWithTitle("Could not retrieve product info", message: errorString)
  177. }
  178. }
  179. func alertForPurchaseResult(_ result: PurchaseResult) -> UIAlertController? {
  180. switch result {
  181. case .success(let product):
  182. print("Purchase Success: \(product.productId)")
  183. return alertWithTitle("Thank You", message: "Purchase completed")
  184. case .error(let error):
  185. print("Purchase Failed: \(error)")
  186. switch error.code {
  187. case .unknown: return alertWithTitle("Purchase failed", message: "Unknown error. Please contact support")
  188. case .clientInvalid: // client is not allowed to issue the request, etc.
  189. return alertWithTitle("Purchase failed", message: "Not allowed to make the payment")
  190. case .paymentCancelled: // user cancelled the request, etc.
  191. return nil
  192. case .paymentInvalid: // purchase identifier was invalid, etc.
  193. return alertWithTitle("Purchase failed", message: "The purchase identifier was invalid")
  194. case .paymentNotAllowed: // this device is not allowed to make the payment
  195. return alertWithTitle("Purchase failed", message: "The device is not allowed to make the payment")
  196. case .storeProductNotAvailable: // Product is not available in the current storefront
  197. return alertWithTitle("Purchase failed", message: "The product is not available in the current storefront")
  198. case .cloudServicePermissionDenied: // user has not allowed access to cloud service information
  199. return alertWithTitle("Purchase failed", message: "Access to cloud service information is not allowed")
  200. case .cloudServiceNetworkConnectionFailed: // the device could not connect to the nework
  201. return alertWithTitle("Purchase failed", message: "Could not connect to the network")
  202. }
  203. }
  204. }
  205. func alertForRestorePurchases(_ results: RestoreResults) -> UIAlertController {
  206. if results.restoreFailedProducts.count > 0 {
  207. print("Restore Failed: \(results.restoreFailedProducts)")
  208. return alertWithTitle("Restore failed", message: "Unknown error. Please contact support")
  209. } else if results.restoredProducts.count > 0 {
  210. print("Restore Success: \(results.restoredProducts)")
  211. return alertWithTitle("Purchases Restored", message: "All purchases have been restored")
  212. } else {
  213. print("Nothing to Restore")
  214. return alertWithTitle("Nothing to restore", message: "No previous purchases were found")
  215. }
  216. }
  217. func alertForVerifyReceipt(_ result: VerifyReceiptResult) -> UIAlertController {
  218. switch result {
  219. case .success(let receipt):
  220. print("Verify receipt Success: \(receipt)")
  221. return alertWithTitle("Receipt verified", message: "Receipt verified remotly")
  222. case .error(let error):
  223. print("Verify receipt Failed: \(error)")
  224. switch error {
  225. case .noReceiptData :
  226. return alertWithTitle("Receipt verification", message: "No receipt data, application will try to get a new one. Try again.")
  227. default:
  228. return alertWithTitle("Receipt verification", message: "Receipt verification failed")
  229. }
  230. }
  231. }
  232. func alertForVerifySubscription(_ result: VerifySubscriptionResult) -> UIAlertController {
  233. switch result {
  234. case .purchased(let expiresDate):
  235. print("Product is valid until \(expiresDate)")
  236. return alertWithTitle("Product is purchased", message: "Product is valid until \(expiresDate)")
  237. case .expired(let expiresDate):
  238. print("Product is expired since \(expiresDate)")
  239. return alertWithTitle("Product expired", message: "Product is expired since \(expiresDate)")
  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 alertForVerifyPurchase(_ result: VerifyPurchaseResult) -> UIAlertController {
  246. switch result {
  247. case .purchased:
  248. print("Product is purchased")
  249. return alertWithTitle("Product is purchased", message: "Product will not expire")
  250. case .notPurchased:
  251. print("This product has never been purchased")
  252. return alertWithTitle("Not purchased", message: "This product has never been purchased")
  253. }
  254. }
  255. func alertForRefreshReceipt(_ result: RefreshReceiptResult) -> UIAlertController {
  256. switch result {
  257. case .success(let receiptData):
  258. print("Receipt refresh Success: \(receiptData.base64EncodedString)")
  259. return alertWithTitle("Receipt refreshed", message: "Receipt refreshed successfully")
  260. case .error(let error):
  261. print("Receipt refresh Failed: \(error)")
  262. return alertWithTitle("Receipt refresh failed", message: "Receipt refresh failed")
  263. }
  264. }
  265. }