I'm trying to create multiple WKWebView views inside of a background process and then add them to a view on the main thread once they are all done loading.
Each of the WKWebView's contains a chart rendered via javascript so the load time takes about a second per WKWebView so I'm trying to offload the processing to the background so the UI isn't blocked.
This works fine when dispatch_get_main_queue is commented out, however the ui is blocked for 5-10 seconds. Only the brown background of the WKWebView shows up, none of the contents from the webpage.
var webViews : [WKWebView] = []
var myQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0);
dispatch_async(myQueue, {
for i in 0...10
{
var url : NSURL? = NSURL(string:"http://google.com")
var req = NSURLRequest(URL:url!)
var webview = WKWebView(frame:CGRectMake(0, height * CGFloat(i), width, height))
webview.loadRequest(req)
webview.backgroundColor = UIColor.brownColor()
self.webViews.append(webview)
}
dispatch_async(dispatch_get_main_queue(),{
for item in self.webViews
{
self.view.addSubview(item)
}
});
});
If I change the
WKWebViewtoUIWebView, there is a crash.Calling a UIKit method from a thread other than main thread is not allowed.
WKWebViewis also aUIViewsubclass. So I suggest you move setting frame and addSubView method out of the block, and put it before you calldispatch_get_global_queue, and insidedispatch_get_global_queueblock, you load the request one by one.Edit
To monitor if a request has finished loading, you can implement
WKNavigationDelegate'sdidFinishNavigationfunction. You can set a counter, make the counter increase by 1 when the function is called, when the counter value is equal to 10, all webviews are fully loaded.And in
viewDidLoad.The result is
creating webviews 1.85267299413681, while time of loading all requests is more than 8 seconds for me. I didn't find a way to decrease the time of creating webviews, I think it takes that much of time to create those views.