Objective-C Tips & Trick - Prioregroup.com
[Objective-C] UIWebView get vertical height
       
back

// 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






Copyright © 1996-2018 Centro Studi Informatica di Danilo Priore. All rights reserved. P.I.10149810581.
prioregroup.com