ViewController.swift 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  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. class ViewController: NSViewController {
  28. let AppBundleId = "com.musevisions.OSX.SwiftyStoreKit"
  29. // MARK: actions
  30. @IBAction func getInfo1(sender: AnyObject?) {
  31. getInfo("1")
  32. }
  33. @IBAction func getInfo2(sender: AnyObject!) {
  34. getInfo("2")
  35. }
  36. @IBAction func purchase1(sender: AnyObject!) {
  37. purchase("1")
  38. }
  39. @IBAction func purchase2(sender: AnyObject!) {
  40. purchase("2")
  41. }
  42. func getInfo(no: String) {
  43. SwiftyStoreKit.retrieveProductsInfo([AppBundleId + ".purchase" + no]) { result in
  44. self.showAlert(self.alertForProductRetrievalInfo(result))
  45. }
  46. }
  47. func purchase(no: String) {
  48. SwiftyStoreKit.purchaseProduct(AppBundleId + ".purchase" + no) { result in
  49. self.showAlert(self.alertForPurchaseResult(result))
  50. }
  51. }
  52. @IBAction func restorePurchases(sender: AnyObject?) {
  53. SwiftyStoreKit.restorePurchases() { results in
  54. self.showAlert(self.alertForRestorePurchases(results))
  55. }
  56. }
  57. @IBAction func verifyReceipt(ender: AnyObject?) {
  58. SwiftyStoreKit.verifyReceipt() { result in
  59. self.showAlert(self.alertForVerifyReceipt(result)) { response in
  60. SwiftyStoreKit.refreshReceipt()
  61. }
  62. }
  63. }
  64. }
  65. // MARK: User facing alerts
  66. extension ViewController {
  67. func alertWithTitle(title: String, message: String) -> NSAlert {
  68. let alert: NSAlert = NSAlert()
  69. alert.messageText = title
  70. alert.informativeText = message
  71. alert.alertStyle = NSAlertStyle.InformationalAlertStyle
  72. return alert
  73. }
  74. func showAlert(alert: NSAlert, handler: ((NSModalResponse) -> Void)? = nil) {
  75. if let window = NSApplication.sharedApplication().keyWindow {
  76. alert.beginSheetModalForWindow(window) { (response: NSModalResponse) in
  77. handler?(response)
  78. }
  79. } else {
  80. let response = alert.runModal()
  81. handler?(response)
  82. }
  83. }
  84. func alertForProductRetrievalInfo(result: SwiftyStoreKit.RetrieveResults) -> NSAlert {
  85. if let product = result.retrievedProducts.first {
  86. let priceString = NSNumberFormatter.localizedStringFromNumber(product.price ?? 0, numberStyle: .CurrencyStyle)
  87. return alertWithTitle(product.localizedTitle ?? "no title", message: "\(product.localizedDescription) - \(priceString)")
  88. }
  89. else if let invalidProductId = result.invalidProductIDs.first {
  90. return alertWithTitle("Could not retrieve product info", message: "Invalid product identifier: \(invalidProductId)")
  91. }
  92. else {
  93. let errorString = result.error?.localizedDescription ?? "Unknown error. Please contact support"
  94. return alertWithTitle("Could not retrieve product info", message: errorString)
  95. }
  96. }
  97. func alertForPurchaseResult(result: SwiftyStoreKit.PurchaseResult) -> NSAlert {
  98. switch result {
  99. case .Success(let productId):
  100. print("Purchase Success: \(productId)")
  101. return alertWithTitle("Thank You", message: "Purchase completed")
  102. case .Error(let error):
  103. print("Purchase Failed: \(error)")
  104. switch error {
  105. case .Failed(let error):
  106. if error.domain == SKErrorDomain {
  107. return alertWithTitle("Purchase failed", message: "Please check your Internet connection or try again later")
  108. }
  109. return alertWithTitle("Purchase failed", message: "Unknown error. Please contact support")
  110. case .InvalidProductId(let productId):
  111. return alertWithTitle("Purchase failed", message: "\(productId) is not a valid product identifier")
  112. case .NoProductIdentifier:
  113. return alertWithTitle("Purchase failed", message: "Product not found")
  114. case .PaymentNotAllowed:
  115. return alertWithTitle("Payments not enabled", message: "You are not allowed to make payments")
  116. }
  117. }
  118. }
  119. func alertForRestorePurchases(results: SwiftyStoreKit.RestoreResults) -> NSAlert {
  120. if results.restoreFailedProducts.count > 0 {
  121. print("Restore Failed: \(results.restoreFailedProducts)")
  122. return alertWithTitle("Restore failed", message: "Unknown error. Please contact support")
  123. }
  124. else if results.restoredProductIds.count > 0 {
  125. print("Restore Success: \(results.restoredProductIds)")
  126. return alertWithTitle("Purchases Restored", message: "All purchases have been restored")
  127. }
  128. else {
  129. print("Nothing to Restore")
  130. return alertWithTitle("Nothing to restore", message: "No previous purchases were found")
  131. }
  132. }
  133. func alertForVerifyReceipt(result: SwiftyStoreKit.VerifyReceiptResult) -> NSAlert {
  134. switch result {
  135. case .Success(let receipt):
  136. print("Verify receipt Success: \(receipt)")
  137. return self.alertWithTitle("Receipt verified", message: "Receipt verified remotly")
  138. case .Error(let error):
  139. print("Verify receipt Failed: \(error)")
  140. 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")
  141. }
  142. }
  143. }