ViewController.swift 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172
  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.retrieveProductInfo(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.RetrieveResult) -> NSAlert {
  85. switch result {
  86. case .Success(let product):
  87. let priceString = NSNumberFormatter.localizedStringFromNumber(product.price ?? 0, numberStyle: .CurrencyStyle)
  88. return alertWithTitle(product.localizedTitle ?? "no title", message: "\(product.localizedDescription) - \(priceString)")
  89. case .Error(let error):
  90. return alertWithTitle("Could not retrieve product info", message: String(error))
  91. }
  92. }
  93. func alertForPurchaseResult(result: SwiftyStoreKit.PurchaseResult) -> NSAlert {
  94. switch result {
  95. case .Success(let productId):
  96. print("Purchase Success: \(productId)")
  97. return alertWithTitle("Thank You", message: "Purchase completed")
  98. case .Error(let error):
  99. print("Purchase Failed: \(error)")
  100. switch error {
  101. case .Failed(let error):
  102. if case ResponseError.RequestFailed(let internalError) = error where internalError.domain == SKErrorDomain {
  103. return alertWithTitle("Purchase failed", message: "Please check your Internet connection or try again later")
  104. }
  105. if (error as NSError).domain == SKErrorDomain {
  106. return alertWithTitle("Purchase failed", message: "Please check your Internet connection or try again later")
  107. }
  108. return alertWithTitle("Purchase failed", message: "Unknown error. Please contact support")
  109. case .NoProductIdentifier:
  110. return alertWithTitle("Purchase failed", message: "Product not found")
  111. case .PaymentNotAllowed:
  112. return alertWithTitle("Payments not enabled", message: "You are not allowed to make payments")
  113. }
  114. }
  115. }
  116. func alertForRestorePurchases(results: SwiftyStoreKit.RestoreResults) -> NSAlert {
  117. if results.restoreFailedProducts.count > 0 {
  118. print("Restore Failed: \(results.restoreFailedProducts)")
  119. return alertWithTitle("Restore failed", message: "Unknown error. Please contact support")
  120. }
  121. else if results.restoredProductIds.count > 0 {
  122. print("Restore Success: \(results.restoredProductIds)")
  123. return alertWithTitle("Purchases Restored", message: "All purchases have been restored")
  124. }
  125. else {
  126. print("Nothing to Restore")
  127. return alertWithTitle("Nothing to restore", message: "No previous purchases were found")
  128. }
  129. }
  130. func alertForVerifyReceipt(result: SwiftyStoreKit.VerifyReceiptResult) -> NSAlert {
  131. switch result {
  132. case .Success(let receipt):
  133. print("Verify receipt Success: \(receipt)")
  134. return self.alertWithTitle("Receipt verified", message: "Receipt verified remotly")
  135. case .Error(let error):
  136. print("Verify receipt Failed: \(error)")
  137. 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")
  138. }
  139. }
  140. }