ios - 使用 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
}
你对解决这个问题有什么建议?
解决方案
这是可能的方法。
1) 使用原生组合发布在ViewRouter
as
class ViewRouter: ObservableObject {
@Published var currentPage: Constants.Views = Constants.Views.login
}
ViewRouter
2) 创建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
,如果您将其用作根视图)AppDelegate
ContentView
MotherView
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
。
推荐阅读
- c# - VS Extension VSIX 保存所有未保存的文档
- algorithm - 关于合并两个排序列表的问题(leetcode 问题 21)
- google-apps-script - 使用 Google 表格控制 Google 日历
- python - 我在 Windows 10 系统上最近安装的 python+otree 组合上使用“git push heroku master”时遇到了一些困难
- java - Thymeleaf 中的动态 HTML
- javascript - 无论用户输入是什么,对用户输入生成随机答案的游戏都会生成相同的答案
- javascript - 图像轮播
- actionscript-3 - AS3:如何严格测试实例是否为对象类型?
- python - 尽管使用了正确的路径,但 Lambda 的层没有导入外部库
- c# - AuthorizationPolicy 基于 url 中的共享密钥,无需身份验证或身份