如何将值从 SceneDelegate 文件传输到 ViewController (Swift 5)
How to transfer a value from a SceneDelegate file to a ViewController (Swift 5)
在 SceneDelegate 方法之一中,我想为另一个 ViewController 中的变量赋值。我怎样才能做到这一点?总是得到零。我尝试了不同的方法,但由于某种原因它们不起作用,我想使用完成处理程序,但似乎我不能在 SceneDelegate 方法中做到这一点
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var viewController: ViewController?
...
//This method works when I click on a cell
func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
if let url = URLContexts.first?.url {
let oauthCompletion: DropboxOAuthCompletion = {
if let authResult = [=12=] {
switch authResult {
case .success:
self.dropboxManager.fetchFiles()
UserDefaults.standard.set(true, forKey:"userAuthorizedInDropbox")
//I want to assign a value here
self.viewController?.someString = "Some Text"
print("Success! User is logged into Dropbox.")
case .cancel:
print("Authorization flow was manually canceled by user!")
case .error(_, let description):
print("Error: \(String(describing: description))")
}
}
}
DropboxClientsManager.handleRedirectURL(url, completion: oauthCompletion)
}
}
...
class ViewController: UIViewController {
...
//But it's still nil
var someString: String?
...
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
dropboxManager.openDropboxAutorization(controller: self)
}
}
.....
class MainTabBarController: UITabBarController {
let viewController: ViewController = ViewController.loadFromStoryboard()
override func viewDidLoad() {
super.viewDidLoad()
viewControllers = [
generateVC(rootViewController: viewController, image: nil, title: "Import")
...
]
private func generateVC(rootViewController: UIViewController, image: UIImage?, title: String) -> UIViewController {
let navigationVC = UINavigationController(rootViewController: rootViewController)
navigationVC.tabBarItem.image = image
navigationVC.tabBarItem.title = NSLocalizedString(title, comment: "")
rootViewController.navigationItem.title = NSLocalizedString(title, comment: "")
return navigationVC
}
}
...
}
您可以从场景委托中的 rootViewController
访问您想要的 ViewController
。在下面的示例中,我认为您想要的视图控制器位于选项卡栏控制器的第一个选项卡中。
if let tabbarController = self.window?.rootViewController as? UITabBarController,
let navigationController = tabbarController.viewControllers?.first as? UINavigationController,
let desiredController = navigationController.viewControllers.first as? ViewController {
desiredController.someString = "some value"
}
但我认为这不是推荐的方法,因为可能有很多情况取决于应用程序或导航堆栈的状态。
您可以做的是在您想要的 ViewController
和 post 添加一个来自 SceneDelegate
的通知,如下所示:
NotificationCenter.default.post(name: Notification.Name(rawValue: "someeventname"), object: "some value")
您可以像这样添加和收听观察者:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
NotificationCenter.default.addObserver(self, selector: #selector(someEventNotificationReceived(notification:)), name: Notification.Name(rawValue: "someeventname"), object: nil)
}
deinit {
NotificationCenter.default.removeObserver(self, name: Notification.Name(rawValue: "someeventname"), object: nil)
}
@objc func someEventNotificationReceived(notification: Notification) {
if let value = notification.object as? String {
//handle the event here
}
}
}
在 SceneDelegate 方法之一中,我想为另一个 ViewController 中的变量赋值。我怎样才能做到这一点?总是得到零。我尝试了不同的方法,但由于某种原因它们不起作用,我想使用完成处理程序,但似乎我不能在 SceneDelegate 方法中做到这一点
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var viewController: ViewController?
...
//This method works when I click on a cell
func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
if let url = URLContexts.first?.url {
let oauthCompletion: DropboxOAuthCompletion = {
if let authResult = [=12=] {
switch authResult {
case .success:
self.dropboxManager.fetchFiles()
UserDefaults.standard.set(true, forKey:"userAuthorizedInDropbox")
//I want to assign a value here
self.viewController?.someString = "Some Text"
print("Success! User is logged into Dropbox.")
case .cancel:
print("Authorization flow was manually canceled by user!")
case .error(_, let description):
print("Error: \(String(describing: description))")
}
}
}
DropboxClientsManager.handleRedirectURL(url, completion: oauthCompletion)
}
}
...
class ViewController: UIViewController {
...
//But it's still nil
var someString: String?
...
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
dropboxManager.openDropboxAutorization(controller: self)
}
}
.....
class MainTabBarController: UITabBarController {
let viewController: ViewController = ViewController.loadFromStoryboard()
override func viewDidLoad() {
super.viewDidLoad()
viewControllers = [
generateVC(rootViewController: viewController, image: nil, title: "Import")
...
]
private func generateVC(rootViewController: UIViewController, image: UIImage?, title: String) -> UIViewController {
let navigationVC = UINavigationController(rootViewController: rootViewController)
navigationVC.tabBarItem.image = image
navigationVC.tabBarItem.title = NSLocalizedString(title, comment: "")
rootViewController.navigationItem.title = NSLocalizedString(title, comment: "")
return navigationVC
}
}
...
}
您可以从场景委托中的 rootViewController
访问您想要的 ViewController
。在下面的示例中,我认为您想要的视图控制器位于选项卡栏控制器的第一个选项卡中。
if let tabbarController = self.window?.rootViewController as? UITabBarController,
let navigationController = tabbarController.viewControllers?.first as? UINavigationController,
let desiredController = navigationController.viewControllers.first as? ViewController {
desiredController.someString = "some value"
}
但我认为这不是推荐的方法,因为可能有很多情况取决于应用程序或导航堆栈的状态。
您可以做的是在您想要的 ViewController
和 post 添加一个来自 SceneDelegate
的通知,如下所示:
NotificationCenter.default.post(name: Notification.Name(rawValue: "someeventname"), object: "some value")
您可以像这样添加和收听观察者:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
NotificationCenter.default.addObserver(self, selector: #selector(someEventNotificationReceived(notification:)), name: Notification.Name(rawValue: "someeventname"), object: nil)
}
deinit {
NotificationCenter.default.removeObserver(self, name: Notification.Name(rawValue: "someeventname"), object: nil)
}
@objc func someEventNotificationReceived(notification: Notification) {
if let value = notification.object as? String {
//handle the event here
}
}
}