【问题标题】:Store values of navigation stack in a dictionary iOS将导航堆栈的值存储在字典 iOS 中
【发布时间】:2019-05-15 09:02:17
【问题描述】:

我需要跟踪用户的导航流程并将其存储在Dictionary 中,每次用户访问我应用中的任何屏幕时。我可以使用代码在控制台输出中看到导航堆栈

navigationController?.viewControllers

但不知道如何将其存储在字典中。

请帮忙

【问题讨论】:

  • 使用dict的目的是什么?
  • 是否需要为每个 1 获取 vc 的名称?
  • @Sh_Khan:是的,我需要每个视图控制器的名称
  • @MahendraGP :实际上捕获 VC 名称的目的是将用户导航存储在 txt 文件中并发送到服务器。为此,我将首先添加流指示,然后将其写入一个文本文件
  • 也许您可以在您的问题中添加一个小示例,例如如果用户访问 vc1 然后转到 vc2 并再次返回到 vc1,那么您希望字典中有什么?

标签: ios swift uiviewcontroller uinavigationcontroller nsmutabledictionary


【解决方案1】:

您可以使用navigationStack 获取所有UIViewControllers 的名称,

let controllers = self.navigationController?.viewControllers.compactMap({ String(describing: type(of: $0.self)) }).joined(separator: "_")
print(controllers) //Output: "VC1_VC2_VC3"

您可以将controllers 字符串存储在您的文件中。

【讨论】:

    【解决方案2】:

    希望这有助于获得视图控制器。按照这个并使用单例存储到全局字典中。

    全局函数:

    public func storeCurrentViewController(_ currentFile: String = #file)
    {
        let className = currentFile.components(separatedBy: "/").last ?? ""
        let classNameArr = className.components(separatedBy: ".")
        print("\n\n--> CurrentViewController:  \(classNameArr[0])")
    
        //*********** Use dictionary and do your logics
    
    }
    

    函数调用:

    override func viewDidLoad() {
        super.viewDidLoad()
        storeCurrentViewController()
    }
    

    【讨论】:

    • 希望这会有所帮助。根据需要存储到字典中。
    【解决方案3】:
    NSArray *viewControllers = [[self navigationController] viewControllers];
                    for( int i=0;i<[viewControllers count];i++){
                        id obj=[viewControllers objectAtIndex:i];    
                        NSLog(@"%@",[obj classNameForClass:[obj class]]);
    }
    

    不确定这是否有效。试一试……

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-05
      • 1970-01-01
      • 1970-01-01
      • 2013-12-06
      • 1970-01-01
      • 2019-03-08
      相关资源
      最近更新 更多