不接收场景相变 [英] Not Receiving scenePhase Changes

查看:20
本文介绍了不接收场景相变的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试执行一些我之前放在我的应用程序委托中的代码,例如在进入后台时保存我的托管对象上下文.我将调用放在了 ScenePhase 的 .onChange 中,但我什么也没得到.这是一个示例项目:

I'm trying to execute some code I'd have previously put in my app delegate, such as saving my managed object context when entering the background. I put the call in the .onChange for the scenePhase, but I'm not getting anything. Here's a sample project:

import SwiftUI

@main
struct PhaseApp: App {
    @Environment(\.scenePhase) private var scenePhase
    
    var body: some Scene {
        WindowGroup {
            Text("Hello, world.")
        }
        .onChange(of: scenePhase) { phase in
            switch phase {
            case .active:
                print("Active")
            case .background:
                print("Background")
            case .inactive:
                print("Inactive")
            @unknown default: break
            }
        }
    }
}

我希望每当我按下 Home 键或点击应用程序时,都会在模拟器或我的测试设备上收到打印命令,但没有任何反应.

I'd expect to get a print command in the Simulator or on my test device whenever I press Home or tap the app, but nothing happens.

推荐答案

使用内部场景根视图(通常是ContentView)

Use inside scene root view (usually ContentView)

使用 Xcode 12/iOS 14 进行测试.

Tested with Xcode 12 / iOS 14 as worked.

struct ContentView: View {
    @Environment(\.scenePhase) private var scenePhase
    var body: some View {
        TestView()
            .onChange(of: scenePhase) { phase in
                switch phase {
                    case .active:
                        print(">> your code is here on scene become active")
                    case .inactive:
                        print(">> your code is here on scene become inactive")
                    case .background:
                        print(">> your code is here on scene go background")
                    default:
                        print(">> do something else in future")
                }
            }
    }
}

这篇关于不接收场景相变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆