微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何将值从SceneDelegate文件传输到ViewControllerSwift 5

如何解决如何将值从SceneDelegate文件传输到ViewControllerSwift 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 = $0 {
      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
    }
   }
...
}

解决方法

您可以从场景委托中的ViewController访问所需的rootViewController。在下面的示例中,我考虑您所需的视图控制器位于选项卡栏控制器的第一个选项卡中。

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中添加一个观察者,并像这样从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,object: nil)
    }

    @objc func someEventNotificationReceived(notification: Notification) {
        if let value = notification.object as? String {
            //handle the event here
        }
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。