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

能否后台加载SubscriptionStoreView以避免启动时出现加载白屏?

解决SubscriptionStoreView首次加载白屏的方案

SubscriptionStoreView本身不支持直接在后台预加载视图内容,因为它的渲染逻辑强依赖StoreKit异步获取的商品数据。不过可以通过以下几种方式优化加载体验,避免白屏:

1. 提前预加载商品数据

在展示SubscriptionStoreView之前,先用SKProductRequest获取目标商品信息,等数据就绪后再初始化并展示视图:

func fetchSubscriptionProducts() {
    let productIDs = Set(["id"])
    let request = SKProductsRequest(productIdentifiers: productIDs)
    request.delegate = self
    request.start()
}

// 实现SKProductsRequestDelegate代理方法
func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) {
    guard !response.products.isEmpty else {
        // 处理商品获取失败的逻辑
        return
    }
    // 商品数据就绪,初始化并展示SubscriptionStoreView
    let subscriptionView = SubscriptionStoreView(productIDs: ["id"])
        .subscriptionStoreButtonLabel(.action)
        .storeButton(.visible, for: .restorePurchases)
        .storeButton(.hidden, for: .cancellation)
    
    // 将视图添加到当前ViewController的视图层级
    let hostingController = UIHostingController(rootView: subscriptionView)
    addChild(hostingController)
    view.addSubview(hostingController.view)
    // 设置布局约束(根据实际需求调整)
    hostingController.view.frame = view.bounds
    hostingController.didMove(toParent: self)
}

提前发起商品请求,能避免视图展示时才触发数据加载,大幅减少白屏时长。

2. 添加自定义加载占位符

在SubscriptionStoreView加载完成前,显示自定义加载视图(比如活动指示器、品牌占位图)替代默认白屏:

struct SubscriptionContainerView: View {
    @State private var isLoading = true
    
    var body: some View {
        SubscriptionStoreView(productIDs: ["id"])
            .subscriptionStoreButtonLabel(.action)
            .storeButton(.visible, for: .restorePurchases)
            .storeButton(.hidden, for: .cancellation)
            .onAppear {
                // 结合商品预请求的完成状态更新isLoading
                // 示例用延迟模拟实际加载,实际需根据真实回调修改
                DispatchQueue.main.asyncAfter(deadline: .now() + 0.8) {
                    isLoading = false
                }
            }
            .overlay(alignment: .center) {
                if isLoading {
                    VStack {
                        ProgressView()
                        Text("加载订阅内容...")
                            .font(.caption)
                            .padding(.top, 8)
                    }
                    .frame(maxWidth: .infinity, maxHeight: .infinity)
                    .background(Color.white)
                }
            }
    }
}

由于SubscriptionStoreView未公开加载状态回调,可通过SKProductsRequest的完成事件来精准控制占位符的显示与隐藏。

3. 延迟添加视图至数据就绪

在ViewController中,先不添加SubscriptionStoreView,等商品数据请求完成后再将其加入视图层级,用户看到的就是已加载完成的视图,彻底避免白屏。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 22:13:11