2
0

ViewController.swift 15 KB

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