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

Swift中从Safari返回App时viewWillAppear未调用的原因及解决方法

问题原因

当通过UIApplication.shared.open(url)打开Safari时,你的App会进入后台,但当前ViewController的view并没有被隐藏或销毁——只是整个App处于后台状态。从Safari返回时,App回到前台,但ViewController的view的可见性没有发生变化,因此viewWillAppear方法不会被触发。

解决方案

可以通过监听App从后台回到前台的通知来实现需求,以下是具体实现方式:

方法:使用NotificationCenter监听激活通知

在你的ViewController中添加通知监听,当App回到前台时调用sellServiceCall:

override func viewDidLoad() {
    super.viewDidLoad()
    // 添加通知监听
    NotificationCenter.default.addObserver(self, selector: #selector(handleAppBecomeActive), name: UIApplication.didBecomeActiveNotification, object: nil)
}

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    // 移除通知监听,避免内存泄漏
    NotificationCenter.default.removeObserver(self, name: UIApplication.didBecomeActiveNotification, object: nil)
}

@objc private func handleAppBecomeActive() {
    // 从Safari返回时会触发这个方法,调用接口
    sellServiceCall()
}

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    sellServiceCall()
}

@IBAction func connectStripeBtn(_ sender: Any) {
    guard let url = URL(string: "someurl") else { return }
    UIApplication.shared.open(url)
}

其他可选方案

  • 使用SceneDelegate(iOS 13+):如果你的App采用场景架构,可以在SceneDelegate的sceneDidBecomeActive(_:)方法中,找到当前显示的ViewController并调用sellServiceCall。
  • 使用AppDelegate:在AppDelegate的applicationDidBecomeActive(_:)方法中发送通知或直接调用目标方法,但这种方式全局生效,适合所有页面都需要执行的场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 12:35:19