ViewController.swift 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  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.retrieveProductInfo(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() { result in
  59. NetworkActivityIndicatorManager.networkOperationFinished()
  60. self.showAlert(self.alertForRestorePurchases(result))
  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.RetrieveResult) -> UIAlertController {
  98. switch result {
  99. case .Success(let product):
  100. let priceString = NSNumberFormatter.localizedStringFromNumber(product.price, numberStyle: .CurrencyStyle)
  101. return alertWithTitle(product.localizedTitle, message: "\(product.localizedDescription) - \(priceString)")
  102. case .Error(let error):
  103. return alertWithTitle("Could not retrieve product info", message: String(error))
  104. }
  105. }
  106. func alertForPurchaseResult(result: SwiftyStoreKit.PurchaseResult) -> UIAlertController {
  107. switch result {
  108. case .Success(let productId):
  109. print("Purchase Success: \(productId)")
  110. return alertWithTitle("Thank You", message: "Purchase completed")
  111. case .Error(let error):
  112. print("Purchase Failed: \(error)")
  113. switch error {
  114. case .Failed(let error):
  115. if case ResponseError.RequestFailed(let internalError) = error where internalError.domain == SKErrorDomain {
  116. return alertWithTitle("Purchase failed", message: "Please check your Internet connection or try again later")
  117. }
  118. if (error as NSError).domain == SKErrorDomain {
  119. return alertWithTitle("Purchase failed", message: "Please check your Internet connection or try again later")
  120. }
  121. return alertWithTitle("Purchase failed", message: "Unknown error. Please contact support")
  122. case .NoProductIdentifier:
  123. return alertWithTitle("Purchase failed", message: "Product not found")
  124. case .PaymentNotAllowed:
  125. return alertWithTitle("Payments not enabled", message: "You are not allowed to make payments")
  126. }
  127. }
  128. }
  129. func alertForRestorePurchases(result: SwiftyStoreKit.RestoreResults) -> UIAlertController {
  130. if result.restoreFailedProducts.count > 0 {
  131. print("Restore Failed: \(result.restoreFailedProducts)")
  132. return alertWithTitle("Restore failed", message: "Unknown error. Please contact support")
  133. }
  134. else if result.restoredProductIds.count > 0 {
  135. print("Restore Success: \(result.restoredProductIds)")
  136. return alertWithTitle("Purchases Restored", message: "All purchases have been restored")
  137. }
  138. else {
  139. print("Nothing to Restore")
  140. return alertWithTitle("Nothing to restore", message: "No previous purchases were found")
  141. }
  142. }
  143. func alertForVerifyReceipt(result: SwiftyStoreKit.VerifyReceiptResult) -> UIAlertController{
  144. switch result {
  145. case .Success(let receipt):
  146. print("Verify receipt Success: \(receipt)")
  147. return alertWithTitle("Receipt verified", message: "Receipt verified remotly")
  148. case .Error(let error):
  149. print("Verify receipt Failed: \(error)")
  150. switch (error) {
  151. case .NoReceiptData :
  152. return alertWithTitle("Receipt verification", message: "No receipt data, application will try to get a new one. Try again.")
  153. default:
  154. return alertWithTitle("Receipt verification", message: "Receipt verification failed")
  155. }
  156. }
  157. }
  158. func alertForRefreshReceipt(result: SwiftyStoreKit.RefreshReceiptResult) -> UIAlertController {
  159. switch result {
  160. case .Success:
  161. print("Receipt refresh Success")
  162. return self.alertWithTitle("Receipt refreshed", message: "Receipt refreshed successfully")
  163. case .Error(let error):
  164. print("Receipt refresh Failed: \(error)")
  165. return self.alertWithTitle("Receipt refresh failed", message: "Receipt refresh failed")
  166. }
  167. }
  168. }