CPDFOfferSubscriptionStoreView.swift 3.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. //
  2. // CPDFOfferSubscriptionStoreView.swift
  3. // PDFReaderPro
  4. //
  5. // Created by zenghong on 1/3/25.
  6. //
  7. import SwiftUI
  8. import StoreKit
  9. @available(iOS 18.0, macOS 15.0, tvOS 18.0, watchOS 11.0, visionOS 2.0, *)
  10. public struct CPDFOfferSubscriptionStoreView: View {
  11. @State private var products: [Product] = []
  12. @State private var tProduct: Product?
  13. @State private var showLoading: Bool = true
  14. @State private var winBack : Product.SubscriptionOffer?
  15. var eligibleOffersCallback: (([String])->Void)?
  16. public var body: some View {
  17. VStack {
  18. if showLoading {
  19. // ProgressView("加载订阅信息中...")
  20. } else {
  21. // SubscriptionStoreView(groupID: "21572797")
  22. SubscriptionStoreView(subscriptions: self.products).preferredSubscriptionOffer { product, subscription, eligibleOffers in
  23. // print("winBackOffers:\(product.subscription?.winBackOffers)")
  24. var string: [String] = []
  25. for offer in eligibleOffers {
  26. if let data = offer.id {
  27. string.append(data)
  28. }
  29. }
  30. eligibleOffersCallback?(string)
  31. return eligibleOffers.first
  32. }
  33. // .onAppear {
  34. // fetchProducts()
  35. // }
  36. // .frame(maxWidth: .infinity, maxHeight: .infinity)
  37. }
  38. }
  39. .onAppear {
  40. fetchProducts()
  41. }
  42. }
  43. public func purchaseWinBackOffer() async {
  44. let purchaseOption = Product.PurchaseOption.winBackOffer(winBack!)
  45. do {
  46. let purchaseResult = try await tProduct!.purchase(options: [purchaseOption])
  47. switch purchaseResult {
  48. case .success(let verificationResult):
  49. switch verificationResult {
  50. case .verified(let transaction):
  51. print("购买成功:\(transaction)")
  52. await transaction.finish()
  53. case .unverified(_, let error):
  54. print("验证失败:\(error)")
  55. }
  56. case .userCancelled:
  57. print("用户取消了购买")
  58. case .pending:
  59. print("购买中")
  60. @unknown default:
  61. print("未知错误")
  62. }
  63. } catch {
  64. print("发生错误:\(error)")
  65. }
  66. }
  67. public func fetchProducts() {
  68. Task {
  69. do {
  70. // 加载订阅组的产品
  71. let identifiers = Set(["com.pdfreaderpro.mac_free.member.all_access_pack_advanced_6months.001"])
  72. let fetchedProducts = try await Product.products(for:identifiers)
  73. // 更新产品信息
  74. DispatchQueue.main.async {
  75. self.products = fetchedProducts
  76. self.tProduct = fetchedProducts.first
  77. self.showLoading = false
  78. }
  79. } catch {
  80. print("无法加载产品: \(error)")
  81. self.showLoading = false
  82. }
  83. }
  84. }
  85. }