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

确认RevenueCat购买后ViewController未实例化问题排查

问题

我编写了如下代码用于识别用户完成购买的操作:

@objc func purchaseTapped(sender: UIButton) {
    print("Tapped") // 此内容已打印
    
    let package = self.packagesAvailableForPurchase[sender.tag]
    
    Purchases.shared.purchasePackage(package) { (transaction, customerInfo, error, userCancelled) in
        if customerInfo?.entitlements.all["AllAccess"]?.isActive == true {
            
            print("Purchased") // 此内容已打印
            
            // 实例化新ViewController(未生效)
            let authenticationViewController = UIStoryboard(name: "Main", bundle: .main).instantiateViewController(identifier: "AuthenticationViewController")
            self.window?.rootViewController = authenticationViewController
            self.window?.makeKeyAndVisible()
        }
        else {
            print("No Access")
        }
    }
}

目前购买成功的日志已打印,但AuthenticationViewController的实例化及页面切换未生效,请问我遗漏了什么?

解决方案
  • 强制在主线程执行UI操作:Purchases的回调默认在后台线程运行,而所有UI更新必须在主线程完成。把页面切换代码包裹到主线程队列里:
    DispatchQueue.main.async {
        let authenticationViewController = UIStoryboard(name: "Main", bundle: .main).instantiateViewController(identifier: "AuthenticationViewController")
        self.window?.rootViewController = authenticationViewController
        self.window?.makeKeyAndVisible()
    }
    
  • 检查window对象是否有效:iOS 13+多场景模式下,self.window可能为空。可以通过应用场景获取当前活跃window:
    DispatchQueue.main.async {
        guard let scene = UIApplication.shared.connectedScenes.first as? UIWindowScene,
              let activeWindow = scene.windows.first else { return }
        let authenticationViewController = UIStoryboard(name: "Main", bundle: .main).instantiateViewController(identifier: "AuthenticationViewController")
        activeWindow.rootViewController = authenticationViewController
        activeWindow.makeKeyAndVisible()
    }
    
  • 验证Storyboard与控制器标识符:确认Main.storyboard中存在标识符为AuthenticationViewController的控制器,且大小写、拼写完全和代码一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 16:45:44