Skip to content

Instantly share code, notes, and snippets.

@priore
Created March 31, 2017 14:21
Show Gist options
  • Save priore/56e5f593c29a1a7aa6bab45dfcaec433 to your computer and use it in GitHub Desktop.
Save priore/56e5f593c29a1a7aa6bab45dfcaec433 to your computer and use it in GitHub Desktop.
UIWebView get height
// file: "UIWebView+Height.h"
#import <UIKit/UIKit.h>
typedef void(^WebViewContentLoaded)(NSString *html, CGSize scrollSize);
@interface UIWebView (Height) <UIWebViewDelegate>
@property (nonatomic, copy) WebViewContentLoaded webLoadedBlock;
- (void)loadURL:(NSURL*)url completion:(WebViewContentLoaded)completion;
@end
// file: "UIWebView+Height.m"
#import "UIWebView+Height.h"
#import <objc/runtime.h>
@implementation UIWebView (Height)
- (WebViewContentLoaded )webLoadedBlock {
return objc_getAssociatedObject(self, @"webLoadedBlock");
}
- (void)setWebLoadedBlock:(WebViewContentLoaded)webLoadedBlock {
objc_setAssociatedObject(self, @"webLoadedBlock", webLoadedBlock, OBJC_ASSOCIATION_COPY_NONATOMIC);
}
- (void)loadURL:(NSURL*)url completion:(WebViewContentLoaded)completion
{
if (self.superview == nil) {
[[UIApplication sharedApplication].keyWindow insertSubview:self atIndex:0];
}
self.webLoadedBlock = completion;
self.delegate = self;
NSURLRequest *req = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:60];
[self loadRequest:req];
}
#pragma mark - UIWebView Delegate
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
// UIWebView object has fully loaded.
NSString *state = [webView stringByEvaluatingJavaScriptFromString:@"document.readyState"];
if ([state isEqualToString:@"complete"])
{
// recupera l'altezza del contenuto della webview
NSString *html = [webView stringByEvaluatingJavaScriptFromString: @"document.body.innerHTML"];
float width = [[webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.scrollWidth"] floatValue];
float height = [[webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.scrollHeight"] floatValue];
if ([self.superview isEqual:[UIApplication sharedApplication].keyWindow]) {
[self removeFromSuperview], self.delegate = nil;
}
if (self.webLoadedBlock)
self.webLoadedBlock(html, CGSizeMake(width, height));
}
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
if (self.webLoadedBlock)
self.webLoadedBlock(nil, CGSizeZero);
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment