首页 > 解决方案 > 使用 SwiftUI 接收 APNS 后显示视图

问题描述

在我的应用收到 APNS 推送通知后,我想显示一个视图。我正在使用 SwiftUI。我按照本教程(https://blckbirds.com/post/how-to-navnigate-between-views-in-swiftui-by-using-an-environmentobject/)创建了一个motherView和一个ViewRouter。

MotherView 看起来像这样:

struct MotherView: View {

//    MARK: - Properties
    @EnvironmentObject var viewRouter: ViewRouter
    @State private var isMenuVisible: Bool = false

    var body: some View {
        VStack {
            if viewRouter.currentPage == Constants.Views.login {
                Login_SwiftUIView()
            } else if viewRouter.currentPage == Constants.Views.main {
                MainView(withMenu: $isMenuVisible)
            } else if viewRouter.currentPage == Constants.Views.menu {
                Menu_SwiftUI(withMenu: $isMenuVisible)
            } else if viewRouter.currentPage == Constants.Views.push {
                PushView()
            }
        }
    }
}

ViewRouter 是一个 ObservableObjectClass

class ViewRouter: ObservableObject {

    let objectWillChange = PassthroughSubject<ViewRouter,Never>()

    var currentPage: Constants.Views = Constants.Views.login {
        didSet {
            objectWillChange.send(self)
        }
    }
}

AppDelegate 在收到 Push-Notification 后调用此函数:

func presentView(with pushNotification: [String: AnyObject]) {
    //Here I want to set the viewRouter.currentPage = Constants.View.push
}

你对解决这个问题有什么建议?

标签: iosswiftswiftuiapple-push-notifications

解决方案


这是可能的方法。

1) 使用原生组合发布在ViewRouteras

class ViewRouter: ObservableObject {
    @Published var currentPage: Constants.Views = Constants.Views.login
}

ViewRouter2) 创建in 的成员实例AppDelegate

class AppDelegate {
   var viewRouter = ViewRouter()

...

func presentView(with pushNotification: [String: AnyObject]) {
    // set here new value
    self.viewRouter.currentPage = Constants.View.push

}

3)SceneDelegate用作环境对象(或者viewRouter,如果您将其用作根视图)AppDelegateContentViewMotherView

class SceneDelegate: UIResponder, UIWindowSceneDelegate {

    var window: UIWindow?

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

        // Use a UIHostingController as window root view controller.
        if let windowScene = scene as? UIWindowScene {

            let appDelegate = UIApplication.shared.delegate as! AppDelegate
            let contentView = ContentView().environmentObject(appDelegate.viewRoute)

            let window = UIWindow(windowScene: windowScene)
            window.rootViewController = UIHostingController(rootView: contentView)

因此,您使用一个在 中ViewRoute修改AppDelegate和处理的对象MotherView


推荐阅读