ViewController.swift 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  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. class ViewController: UIViewController {
  28. let AppBundleId = "com.musevisions.iOS.SwiftyStoreKit"
  29. // MARK: actions
  30. @IBAction func getInfo1() {
  31. getInfo("1")
  32. }
  33. @IBAction func getInfo2() {
  34. getInfo("2")
  35. }
  36. @IBAction func purchase1() {
  37. purchase("1")
  38. }
  39. @IBAction func purchase2() {
  40. purchase("2")
  41. }
  42. func getInfo(no: String) {
  43. NetworkActivityIndicatorManager.networkOperationStarted()
  44. SwiftyStoreKit.retrieveProductsInfo([AppBundleId + ".purchase" + no]) { result in
  45. NetworkActivityIndicatorManager.networkOperationFinished()
  46. self.showAlert(self.alertForProductRetrievalInfo(result))
  47. }
  48. }
  49. func purchase(no: String) {
  50. NetworkActivityIndicatorManager.networkOperationStarted()
  51. SwiftyStoreKit.purchaseProduct(AppBundleId + ".purchase" + no) { result in
  52. NetworkActivityIndicatorManager.networkOperationFinished()
  53. self.showAlert(self.alertForPurchaseResult(result))
  54. }
  55. }
  56. @IBAction func restorePurchases() {
  57. NetworkActivityIndicatorManager.networkOperationStarted()
  58. SwiftyStoreKit.restorePurchases() { results in
  59. NetworkActivityIndicatorManager.networkOperationFinished()
  60. self.showAlert(self.alertForRestorePurchases(results))
  61. }
  62. }
  63. @IBAction func verifyReceipt() {
  64. NetworkActivityIndicatorManager.networkOperationStarted()
  65. SwiftyStoreKit.verifyReceipt() { result in
  66. NetworkActivityIndicatorManager.networkOperationFinished()
  67. self.showAlert(self.alertForVerifyReceipt(result))
  68. if case .Error(let error) = result {
  69. if case .NoReceiptData = error {
  70. self.refreshReceipt()
  71. }
  72. }
  73. }
  74. }
  75. func refreshReceipt() {
  76. SwiftyStoreKit.refreshReceipt { (result) -> () in
  77. self.showAlert(self.alertForRefreshReceipt(result))
  78. }
  79. }
  80. override func preferredStatusBarStyle() -> UIStatusBarStyle {
  81. return .LightContent
  82. }
  83. }
  84. // MARK: User facing alerts
  85. extension ViewController {
  86. func alertWithTitle(title: String, message: String) -> UIAlertController {
  87. let alert = UIAlertController(title: title, message: message, preferredStyle: .Alert)
  88. alert.addAction(UIAlertAction(title: "OK", style: .Cancel, handler: nil))
  89. return alert
  90. }
  91. func showAlert(alert: UIAlertController) {
  92. guard let _ = self.presentedViewController else {
  93. self.presentViewController(alert, animated: true, completion: nil)
  94. return
  95. }
  96. }
  97. func alertForProductRetrievalInfo(result: SwiftyStoreKit.RetrieveResults) -> UIAlertController {
  98. if let product = result.retrievedProducts.first {
  99. let priceString = NSNumberFormatter.localizedStringFromNumber(product.price, numberStyle: .CurrencyStyle)
  100. return alertWithTitle(product.localizedTitle, message: "\(product.localizedDescription) - \(priceString)")
  101. }
  102. else if let invalidProductId = result.invalidProductIDs.first {
  103. return alertWithTitle("Could not retrieve product info", message: "Invalid product identifier: \(invalidProductId)")
  104. }
  105. else {
  106. let errorString = result.error?.localizedDescription ?? "Unknown error. Please contact support"
  107. return alertWithTitle("Could not retrieve product info", message: errorString)
  108. }
  109. }
  110. func alertForPurchaseResult(result: SwiftyStoreKit.PurchaseResult) -> UIAlertController {
  111. switch result {
  112. case .Success(let productId):
  113. print("Purchase Success: \(productId)")
  114. return alertWithTitle("Thank You", message: "Purchase completed")
  115. case .Error(let error):
  116. print("Purchase Failed: \(error)")
  117. switch error {
  118. case .Failed(let error):
  119. if error.domain == SKErrorDomain {
  120. return alertWithTitle("Purchase failed", message: "Please check your Internet connection or try again later")
  121. }
  122. return alertWithTitle("Purchase failed", message: "Unknown error. Please contact support")
  123. case .InvalidProductId(let productId):
  124. return alertWithTitle("Purchase failed", message: "\(productId) is not a valid product identifier")
  125. case .NoProductIdentifier:
  126. return alertWithTitle("Purchase failed", message: "Product not found")
  127. case .PaymentNotAllowed:
  128. return alertWithTitle("Payments not enabled", message: "You are not allowed to make payments")
  129. }
  130. }
  131. }
  132. func alertForRestorePurchases(results: SwiftyStoreKit.RestoreResults) -> UIAlertController {
  133. if results.restoreFailedProducts.count > 0 {
  134. print("Restore Failed: \(results.restoreFailedProducts)")
  135. return alertWithTitle("Restore failed", message: "Unknown error. Please contact support")
  136. }
  137. else if results.restoredProductIds.count > 0 {
  138. print("Restore Success: \(results.restoredProductIds)")
  139. return alertWithTitle("Purchases Restored", message: "All purchases have been restored")
  140. }
  141. else {
  142. print("Nothing to Restore")
  143. return alertWithTitle("Nothing to restore", message: "No previous purchases were found")
  144. }
  145. }
  146. func alertForVerifyReceipt(result: SwiftyStoreKit.VerifyReceiptResult) -> UIAlertController{
  147. switch result {
  148. case .Success(let receipt):
  149. print("Verify receipt Success: \(receipt)")
  150. return alertWithTitle("Receipt verified", message: "Receipt verified remotly")
  151. case .Error(let error):
  152. print("Verify receipt Failed: \(error)")
  153. switch (error) {
  154. case .NoReceiptData :
  155. return alertWithTitle("Receipt verification", message: "No receipt data, application will try to get a new one. Try again.")
  156. default:
  157. return alertWithTitle("Receipt verification", message: "Receipt verification failed")
  158. }
  159. }
  160. }
  161. func alertForRefreshReceipt(result: SwiftyStoreKit.RefreshReceiptResult) -> UIAlertController {
  162. switch result {
  163. case .Success:
  164. print("Receipt refresh Success")
  165. return self.alertWithTitle("Receipt refreshed", message: "Receipt refreshed successfully")
  166. case .Error(let error):
  167. print("Receipt refresh Failed: \(error)")
  168. return self.alertWithTitle("Receipt refresh failed", message: "Receipt refresh failed")
  169. }
  170. }
  171. }