ViewController.swift 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  1. //
  2. // ViewController.swift
  3. // SwiftStoreOSXDemo
  4. //
  5. // Created by phimage on 22/12/15.
  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 Cocoa
  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. }
  34. class ViewController: NSViewController {
  35. let AppBundleId = "com.musevisions.OSX.SwiftyStoreKit"
  36. let Purchase1 = RegisteredPurchase.Purchase1.rawValue
  37. let Purchase2 = RegisteredPurchase.AutoRenewablePurchase.rawValue
  38. // MARK: actions
  39. @IBAction func getInfo1(sender: AnyObject?) {
  40. getInfo(Purchase1)
  41. }
  42. @IBAction func purchase1(sender: AnyObject?) {
  43. purchase(Purchase1)
  44. }
  45. @IBAction func verifyPurchase1(sender: AnyObject?) {
  46. verifyPurchase(Purchase1)
  47. }
  48. @IBAction func getInfo2(sender: AnyObject?) {
  49. getInfo(Purchase2)
  50. }
  51. @IBAction func purchase2(sender: AnyObject?) {
  52. purchase(Purchase2)
  53. }
  54. @IBAction func verifyPurchase2(sender: AnyObject?) {
  55. verifyPurchase(Purchase2)
  56. }
  57. func getInfo(purchaseName: String) {
  58. SwiftyStoreKit.retrieveProductsInfo([AppBundleId + "." + purchaseName]) { result in
  59. self.showAlert(self.alertForProductRetrievalInfo(result))
  60. }
  61. }
  62. func purchase(purchaseName: String) {
  63. SwiftyStoreKit.purchaseProduct(AppBundleId + "." + purchaseName) { result in
  64. self.showAlert(self.alertForPurchaseResult(result))
  65. }
  66. }
  67. @IBAction func restorePurchases(sender: AnyObject?) {
  68. SwiftyStoreKit.restorePurchases() { results in
  69. self.showAlert(self.alertForRestorePurchases(results))
  70. }
  71. }
  72. @IBAction func verifyReceipt(sender: AnyObject?) {
  73. SwiftyStoreKit.verifyReceipt() { result in
  74. self.showAlert(self.alertForVerifyReceipt(result)) { response in
  75. SwiftyStoreKit.refreshReceipt()
  76. }
  77. }
  78. }
  79. func verifyPurchase(purchaseName: String) {
  80. SwiftyStoreKit.verifyReceipt() { result in
  81. switch result {
  82. case .Success(let receipt):
  83. let purchaseResult = SwiftyStoreKit.verifyPurchase(
  84. productId: self.AppBundleId + "." + purchaseName,
  85. inReceipt: receipt,
  86. validUntil: nil
  87. )
  88. self.showAlert(self.alertForVerifyPurchase(purchaseResult))
  89. case .Error(_):
  90. self.showAlert(self.alertForVerifyReceipt(result))
  91. }
  92. }
  93. }
  94. }
  95. // MARK: User facing alerts
  96. extension ViewController {
  97. func alertWithTitle(title: String, message: String) -> NSAlert {
  98. let alert: NSAlert = NSAlert()
  99. alert.messageText = title
  100. alert.informativeText = message
  101. alert.alertStyle = NSAlertStyle.InformationalAlertStyle
  102. return alert
  103. }
  104. func showAlert(alert: NSAlert, handler: ((NSModalResponse) -> Void)? = nil) {
  105. if let window = NSApplication.sharedApplication().keyWindow {
  106. alert.beginSheetModalForWindow(window) { (response: NSModalResponse) in
  107. handler?(response)
  108. }
  109. } else {
  110. let response = alert.runModal()
  111. handler?(response)
  112. }
  113. }
  114. func alertForProductRetrievalInfo(result: SwiftyStoreKit.RetrieveResults) -> NSAlert {
  115. if let product = result.retrievedProducts.first {
  116. let priceString = NSNumberFormatter.localizedStringFromNumber(product.price ?? 0, numberStyle: .CurrencyStyle)
  117. return alertWithTitle(product.localizedTitle ?? "no title", message: "\(product.localizedDescription) - \(priceString)")
  118. }
  119. else if let invalidProductId = result.invalidProductIDs.first {
  120. return alertWithTitle("Could not retrieve product info", message: "Invalid product identifier: \(invalidProductId)")
  121. }
  122. else {
  123. let errorString = result.error?.localizedDescription ?? "Unknown error. Please contact support"
  124. return alertWithTitle("Could not retrieve product info", message: errorString)
  125. }
  126. }
  127. func alertForPurchaseResult(result: SwiftyStoreKit.PurchaseResult) -> NSAlert {
  128. switch result {
  129. case .Success(let productId):
  130. print("Purchase Success: \(productId)")
  131. return alertWithTitle("Thank You", message: "Purchase completed")
  132. case .Error(let error):
  133. print("Purchase Failed: \(error)")
  134. switch error {
  135. case .Failed(let error):
  136. if error.domain == SKErrorDomain {
  137. return alertWithTitle("Purchase failed", message: "Please check your Internet connection or try again later")
  138. }
  139. return alertWithTitle("Purchase failed", message: "Unknown error. Please contact support")
  140. case .InvalidProductId(let productId):
  141. return alertWithTitle("Purchase failed", message: "\(productId) is not a valid product identifier")
  142. case .NoProductIdentifier:
  143. return alertWithTitle("Purchase failed", message: "Product not found")
  144. case .PaymentNotAllowed:
  145. return alertWithTitle("Payments not enabled", message: "You are not allowed to make payments")
  146. }
  147. }
  148. }
  149. func alertForRestorePurchases(results: SwiftyStoreKit.RestoreResults) -> NSAlert {
  150. if results.restoreFailedProducts.count > 0 {
  151. print("Restore Failed: \(results.restoreFailedProducts)")
  152. return alertWithTitle("Restore failed", message: "Unknown error. Please contact support")
  153. }
  154. else if results.restoredProductIds.count > 0 {
  155. print("Restore Success: \(results.restoredProductIds)")
  156. return alertWithTitle("Purchases Restored", message: "All purchases have been restored")
  157. }
  158. else {
  159. print("Nothing to Restore")
  160. return alertWithTitle("Nothing to restore", message: "No previous purchases were found")
  161. }
  162. }
  163. func alertForVerifyReceipt(result: SwiftyStoreKit.VerifyReceiptResult) -> NSAlert {
  164. switch result {
  165. case .Success(let receipt):
  166. print("Verify receipt Success: \(receipt)")
  167. return self.alertWithTitle("Receipt verified", message: "Receipt verified remotly")
  168. case .Error(let error):
  169. print("Verify receipt Failed: \(error)")
  170. return self.alertWithTitle("Receipt verification failed", message: "The application will exit to create receipt data. You must have signed the application with your developer id to test and be outside of XCode")
  171. }
  172. }
  173. func alertForVerifyPurchase(result: SwiftyStoreKit.VerifyPurchaseResult) -> NSAlert {
  174. switch result {
  175. case .Purchased(let expiresDate):
  176. if let expiresDate = expiresDate {
  177. return alertWithTitle("Product is purchased", message: "Product is valid until \(expiresDate)")
  178. }
  179. return alertWithTitle("Product is purchased", message: "Product will not expire")
  180. case .Expired(let expiresDate): // Only for Automatically Renewable Subscription
  181. return alertWithTitle("Product expired", message: "Product is expired since \(expiresDate)")
  182. case .NotPurchased:
  183. return alertWithTitle("Not purchased", message: "This product has never been purchased")
  184. }
  185. }
  186. }