【问题标题】:SwiftUI View stops updating when application goes to background当应用程序进入后台时,SwiftUI View 停止更新
【发布时间】:2019-12-25 03:46:42
【问题描述】:

我正在使用 Spotify APK 来授权与 Spotify 应用的连接。与 Spotify 的所有通信都是通过 Scene Delegate 完成的。我的问题是,当我要求授权并且我往返于 Spotify 应用程序时,当前视图似乎停止更新 @Published 变量更改。但是,我希望在成功授权/连接后改变视图。

我尝试通过对不同变量的不同更改来更新 MainView,但似乎无论我做什么,一旦应用离开并重新进入前台,视图就会停止更新并更改已发布的变量。

场景代理:

class SceneDelegate: UIResponder, UIWindowSceneDelegate, SPTAppRemoteDelegate, SPTAppRemotePlayerStateDelegate {

    @ObservedObject var MainVM = MainViewModel()

    func appRemoteDidEstablishConnection(_ appRemote: SPTAppRemote) {
        MainVM.viewSwitch = false
    }

}

主视图模型:

class MainViewModel: ObservableObject {

    @Published var viewSwitch: Bool = true

    var appRemote: SPTAppRemote {
        get {
            let scene = UIApplication.shared.connectedScenes.first
            let sd : SceneDelegate = (scene?.delegate as? SceneDelegate)!
            return sd.appRemote
        }
    }

    func connectAppRemote() {
        appRemote.authorizeAndPlayURI("")
    }

}

主视图:

struct MainView: View {

    @ObservedObject var MainVM = MainViewModel()

    var body: some View {
        if MainVM.viewSwitch {
            Text("View 1 Displayed")
        } else {
            Text("View 2 Displayed")
        }
    }
    .onAppear {
        MainVM.connectAppRemote()
    }
}

【问题讨论】:

  • 嗨,Vincent,我刚开始开发 SwiftUI 应用程序并遇到了这个问题。你是如何安装框架的?我链接了桥接头,但在构建和运行时出现错误"Extra info about plist: ACL=<not found>" 。你经历过吗?
  • 很抱歉,我无法为您提供 Spotify APK 的帮助。我很久以前就停止使用它了,我不记得我发现的过程或障碍:(
  • 不用担心,感谢您回复我。如果有什么突然出现在记忆中,请随时告诉我。祝你好运

标签: ios swift xcode swiftui


【解决方案1】:

您使用不同的对象:

A. SceneDelegate 有自己的实例(顺便说一句,这里你不需要ObservedObject

class SceneDelegate: UIResponder, UIWindowSceneDelegate, 
                     SPTAppRemoteDelegate, SPTAppRemotePlayerStateDelegate {

    @ObservedObject var MainVM = MainViewModel()

B. MainView有自己的

struct MainView: View {

    @ObservedObject var MainVM = MainViewModel() // << recreated

您需要将SceneDelegate 中的那个传递为environmentObjectMainView,就像

func scene(_ scene: UIScene, willConnectTo session: UISceneSession, 
           options connectionOptions: UIScene.ConnectionOptions) {

    let contentView = MainView().environmentObject(MainVM)

并相应声明

struct MainView: View {

    @EnvironmentObject var MainVM: MainViewModel

【讨论】:

  • 这正是我所需要的!非常感谢!
猜你喜欢
  • 2014-12-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-13
相关资源
最近更新 更多