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

从SafariViewController返回后Swift应用出现白屏问题求助

解决SafariViewController返回后白屏的问题

嘿,我来帮你排查这个白屏问题~其实原因很简单:你的SavedViewController本身的视图完全是空的——既没设置背景色,也没添加任何UI控件,所以当你关闭SafariViewController回到这个控制器时,自然看到的就是空白状态。另外还有个小细节:你不需要手动实现safariViewControllerDidFinish方法,系统默认会在用户点击“完成”按钮时自动关闭SFSafariViewController,你重写这个方法重复调用dismiss虽然不会直接导致白屏,但属于多余操作。

下面根据你的实际需求给两种解决方案:

情况1:SavedViewController本身需要展示内容

如果这个控制器是你应用里的一个正式页面(比如收藏页),需要展示具体内容,那你只需要先给它的视图添加UI元素或者设置背景色就行,示例代码如下:

import UIKit
import SafariServices

class SavedViewController: UIViewController, SFSafariViewControllerDelegate {
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 先配置当前页面的基础样式和内容
        view.backgroundColor = .systemBackground // 适配系统深浅模式的背景色
        // 添加一个页面标题示例
        let titleLabel = UILabel()
        titleLabel.text = "我的收藏页面"
        titleLabel.font = .systemFont(ofSize: 20, weight: .semibold)
        titleLabel.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(titleLabel)
        
        // 用AutoLayout布局标题
        NSLayoutConstraint.activate([
            titleLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor),
            titleLabel.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 20)
        ])
        
        // 再弹出SafariViewController
        if let link = URL(string: "https://google.com") {
            let safariVC = SFSafariViewController(url: link)
            safariVC.delegate = self
            present(safariVC, animated: true)
        }
    }

    // 这个方法可以直接删除,系统会自动处理完成按钮的关闭逻辑
    // func safariViewControllerDidFinish(_ controller: SFSafariViewController) {
    //     dismiss(animated:true, completion: nil)
    // }
}

情况2:SavedViewController只是临时中转打开SafariVC

如果这个控制器不需要展示任何内容,只是用来触发打开SafariVC的中转页,那更合理的做法是直接从需要触发的页面(比如首页、列表页)弹出SafariVC,而不是用空控制器中转。如果必须保留这个中转逻辑,可以在关闭SafariVC后直接回到上一个页面,比如如果是通过导航栈push进来的:

import UIKit
import SafariServices

class SavedViewController: UIViewController, SFSafariViewControllerDelegate {
    override func viewDidLoad() {
        super.viewDidLoad()
        // 至少给视图设置个背景色,避免中转时的突兀感
        view.backgroundColor = .systemBackground
        
        if let link = URL(string: "https://google.com") {
            let safariVC = SFSafariViewController(url: link)
            safariVC.delegate = self
            present(safariVC, animated: true)
        }
    }

    func safariViewControllerDidFinish(_ controller: SFSafariViewController) {
        // 先关闭SafariVC,再pop回上一个控制器
        controller.dismiss(animated: true) { [weak self] in
            self?.navigationController?.popViewController(animated: true)
        }
    }
}

最后补充个小提醒:哪怕是临时页面,也建议给视图设置背景色,这样就不会出现“白屏”的视觉错觉啦~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:59:28