首页 文章

AppDelegate访问ViewController

提问于
浏览
2

在我的xcode 9.2 swift 4项目中,我有两个类,一个是 AppDelegate ,我处理所有应用程序特定的功能(如订阅和接收推送通知)和ViewController( Main.storyboard id is ShitstuffController ),我处理我的 WKWebView

我想要做的是,当应用程序处于非活动状态或在后台并且用户收到并点击本地通知时,打开我的 ViewController's WKWebView 中该通知中收到的链接 .

我试图像这样访问 ViewController

// AppDelegate.swift code
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let controller = storyboard.instantiateViewController(withIdentifier: "ShitstuffController")
controller.loadViewIfNeeded();

print(controller);

在这一点上,我得到了

<Application.ViewController: 0x105c200a0>

其中 Application 是我的实际应用程序名称,所以我假设我成功访问了我的 ViewController ,但是当我尝试从中调用方法时,例如

// ViewController.swift code
func getDictionaryValue(string: String) -> String {
    let dictionary = Bundle.main.infoDictionary!;
    let version = dictionary[string] as! String;
    return version;
}

喜欢

// AppDelegate.swift code
controller.getDictionaryValue(string: "CFBundleDisplayName");

我收到错误 Value of type 'UIViewController' has no member 'getDictionaryValue'

1 回答

  • 2

    你的 ShitstuffController 不是 UIViewController 类实际上是一个 UIViewController 子类,它是 ViewController 所以你需要强制转换为 ViewController

    if let controller = storyboard.instantiateViewController(withIdentifier: "ShitstuffController") as? ViewController {
      controller.loadViewIfNeeded();
      controller.getDictionaryValue(string: "CFBundleDisplayName");
      print(controller); 
    }
    

    那么你就可以调用 getDictionaryValue 方法了

相关问题