You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

StoreKit2中ProductView用storeButton恢复购买无效的解决办法咨询

解决StoreKit2中ProductView无法显示恢复购买按钮的问题

ProductView的.storeButton修饰符并不支持.restorePurchases选项——因为恢复购买是全局操作,不属于单个商品的交互范围,所以直接用这个修饰符不会生效。以下是可行的解决方法:

手动添加恢复购买按钮

放弃依赖ProductView的修饰符,单独创建按钮并调用StoreKit的恢复交易API:

示例代码

import StoreKit

struct SingleProductView: View {
    let targetProduct: Product
    
    var body: some View {
        VStack(spacing: 20) {
            // 展示单个商品的ProductView
            ProductView(targetProduct)
                .storeButton(.visible, for: .cancellation) // 仅保留商品相关的操作按钮
            
            // 自定义恢复购买按钮
            Button("恢复购买") {
                Task {
                    do {
                        // 调用恢复交易API
                        let restoredTransactions = try await Transaction.restore()
                        
                        // 处理恢复完成后的逻辑
                        if !restoredTransactions.isEmpty {
                            // 比如更新用户权限、提示恢复成功
                            print("成功恢复 \(restoredTransactions.count) 笔交易")
                        } else {
                            print("没有可恢复的购买项目")
                        }
                    } catch {
                        print("恢复购买失败:\(error.localizedDescription)")
                    }
                }
            }
            .buttonStyle(.borderedProminent)
            .padding(.horizontal)
        }
        .padding()
    }
}

额外说明

  • ProductView的.storeButton仅支持与当前展示商品直接相关的操作,比如发起购买、取消订阅(仅适用于订阅类商品),恢复购买是全局行为,因此Apple未在该修饰符中提供支持。
  • 手动实现的方式不仅能解决按钮不显示的问题,还能让你完全自定义按钮的样式、位置,同时灵活处理恢复成功/失败后的业务逻辑,比如同步用户的已购内容状态。

内容的提问来源于stack exchange,提问作者Chris L

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 18:52:02