Background: In order to make web requests to an API endpoint, I need to scrape a website and retrieve a token every 25-30 seconds. I'm doing this with a WKWebView and injecting some custom JavaScript using WKUserScript to retrieve AJAX response headers containing the token. Please focus on the question specifically and not on this background information - I'm attempting this entirely for my own educational purposes.
目标
我将拥有不同的“模型”类,甚至只是其他 UIViewController,它们可能需要调用共享的 UIViewController 来检索此 token 以发出经过身份验证的请求。
也许我可以将其抽象为一个“Sdk”类。无论如何,这个“模型”SDK 类可以被任何其他 ViewController 实例化和使用。
更多信息
我希望能够调用 WKWebView 的 UIViewController 并检索一些数据。除非我每 25 秒重新创建一次,否则我需要在后台运行它或共享它。我希望能够在“后台”运行 UIViewController,并在 WKWebView 完成任务后从中接收一些信息。
我知道有多种方式可以与另一个 ViewController 通信,包括委托(delegate)和转接。但是,我不确定这些是否可以帮助我保留包含 WKWebView 的 View 存在于后台,以便我可以调用它的 ViewController 并让它重新执行抓取。委托(delegate)可能适用于普通代码,但对于必须存在 View 的代码呢?每次不同的模型或 View Controller 尝试获取此 token 时,我是否都必须动态地重新创建此WKWebView?
One post建议使用 ContainerViewControllers。由此,我收集到,在“主”ViewController(包含其他 View Controller 的那个)中,我可以放置隐藏的WKWebView来完成它的事情并与子级通信通过委托(delegate)以这种方式查看 Controller 。
另一篇文章建议使用 AppDelegate 并将其设为共享服务。我完全反对使用 Singleton,因为它被广泛认为是一种反模式。必须有另一种方法,即使稍微复杂一点,也可以帮助我做我想做的事,而无需诉诸这种“作弊”。
This post讨论了多个 ViewController 之间的通信,但我不知道当某些东西需要保持运行和执行时这会有什么用处。
还有其他方法可以做到这一点吗?使用强指针在后台线程中运行某些内容,这样它就不会被丢弃?我使用的是 Xcode 9.2、Swift 4 和 iOS 11。由于我对 iOS 编程非常陌生,因此任何有关此的小代码示例将不胜感激。
最佳答案
不幸的是,WKWebView
必须位于 View 层次结构中才能使用它。您必须将其添加为屏幕 View Controller 的 subview 。
这对我来说很好。我将其添加到屏幕外,因此它不可见。隐藏属性或许也能发挥作用。无论哪种方式,您都必须调用 addSubview
才能使其正常工作。
关于ios - 保持 WKWebView 及其 UIViewController 在后台运行并可从多个 ViewController 访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47698980/