gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 14:57:41 25 4
gpt4 key购买 nike

在我的 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 的请求 url 加载在 viewDidLoad 方法中的内容 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");
}

主要思想是在 AppDelegate 中调用 controller.loadViewIfNeeded(); 之前调用它来覆盖我在 viewDidLoad 中加载的默认 url 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);
}

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

控制台日志是

 ----- Link is set
----- View did load
true
https://google.com
https://google.com

但是为什么?为什么它加载“默认”url?

最佳答案

你不应该那样做。

简单地添加一个属性到你的 View Controller :

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"

关于ios - 使用从 AppDelegate 传递的参数覆盖 ViewController viewDidLoad 方法参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49173930/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com