使用从AppDelegate传递的参数覆盖ViewController viewDidLoad方法参数

时间:2018-03-08 13:11:08

标签: ios swift

在我的"webpackDev": "npm run clean && export NODE_ENV=development && npx webpack", "webpackProd": "npm run clean && export NODE_ENV=production && npx webpack -p" 我正在访问和调用AppDelegate.swift这样的方法

ViewController.swift

并且简单地调用返回一些东西的方法工作正常,但是,在我的情况下,我需要更改let storyboard = UIStoryboard(name: "Main", bundle: nil) if let controller = storyboard.instantiateViewController(withIdentifier: "ShitstuffController") as? ViewController { controller.loadViewIfNeeded(); controller.viewControllerCustomMethod(); // <-- method from ViewController.swift } WKWebView viewDidLoad方法中加载的{@ 1}}的请求网址,以及我试图以这种方式实现它

ViewController

其中let storyboard = UIStoryboard(name: "Main", bundle: nil) if let controller = storyboard.instantiateViewController(withIdentifier: "ShitstuffController") as? ViewController { controller.overrideWebViewURL(url: "https://google.com"); controller.loadViewIfNeeded(); } overrideWebViewURL方法,看起来像

ViewController

主要想法是在func overrideWebViewURL(url: String) { notificationProvidedLink = url; isDidLaunchFromNotification = true; print(" ----- Link is set"); } 中调用controller.loadViewIfNeeded();之前调用它来覆盖我在AppDelegate的{​​{1}}加载的默认网址,这里是完整的逻辑代码

viewDidLoad

这是问题,尽管我实际上覆盖了请求网址(我可以通过控制台输出看到它),ViewController仍然加载我亚马逊而不是谷歌。

控制台日志

// AppDelegate.swift
let storyboard = UIStoryboard(name: "Main", bundle: nil)
if let controller = storyboard.instantiateViewController(withIdentifier: "ShitstuffController") as? ViewController {
    controller.overrideWebViewURL(url: link);
    controller.loadViewIfNeeded();
}


//ViewController.swift

var isDidLaunchFromNotification = false
var notificationProvidedLink = "";

func overrideWebViewURL(url: String) {
    notificationProvidedLink = url;
    isDidLaunchFromNotification = true;

    print(" ----- Link is set");
}

override func viewDidLoad() {
    super.viewDidLoad()

    print(" ----- View did load");

    print(isDidLaunchFromNotification);
    print(notificationProvidedLink);

    var url = URL(string: "https://amazon.com");
    if(isDidLaunchFromNotification == true && notificationProvidedLink != "") {
        url = URL(string: notificationProvidedLink);
    }

    var urlRequest = URLRequest(url: url!);

    webView.navigationDelegate = self;
    webView.uiDelegate = self;


    print(urlRequest);

    webView.load(urlRequest);
}

但为什么呢?为什么它加载&#34;默认&#34; URL?

1 个答案:

答案 0 :(得分:1)

你不应该这样做。

只需向视图控制器添加一个属性:

var link: String {
    didSet {
        let url = URL(string: link)
        var urlRequest = URLRequest(url: url!)

        webView.navigationDelegate = self
        webView.uiDelegate = self
        webView.load(urlRequest)
    }
}

在你的appDelegate中:

let viewController = MyViewController()
viewController.link = "www.mylink.com"