EDIT:
To get the best possible height calculation, in the end I did a few things to get the best height:
- I set the size of the webview to be really large and then load the content.
- Once the content is loaded (KVO notification) I resize the view using the method below.
- I then run the size function again and I get a new size and resize my view once again.
The above got the most accurate results for me.
ORIGINAL:
I've tried the scroll view KVO and I've tried evaluating javascript on the document, using clientHeight
, offsetHeight
, etc...
What worked for me eventually is: document.body.scrollHeight
. Or use the scrollHeight
of your top most element, e.g. a container div
.
I listen to the loading
WKWebview property changes using KVO:
[webview addObserver: self forKeyPath: NSStringFromSelector(@selector(loading)) options: NSKeyValueObservingOptionNew context: nil];
And then:
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
if(object == self.webview && [keyPath isEqualToString: NSStringFromSelector(@selector(loading))]) {
NSNumber *newValue = change[NSKeyValueChangeNewKey];
if(![newValue boolValue]) {
[self updateWebviewFrame];
}
}
}
The updateWebviewFrame
implementation:
[self.webview evaluateJavaScript: @"document.body.scrollHeight" completionHandler: ^(id response, NSError *error) {
CGRect frame = self.webview.frame;
frame.size.height = [response floatValue];
self.webview.frame = frame;
}];