Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIWebView: Delegate won't be called

Tags:

objective-c

I try to calculate the size of a UIWebView with a given content, but without showing the view. I only need to know the size.

My Problem: When I execute the code, the delegate of the UIWebView isn't called. Why?

MessageSizeCaluclator.h

#import < Foundation/Foundation.h>

@class Message;

@interface MessageSizeCaluclator : NSObject <UIWebViewDelegate>

- (id)initWithMessage:(Message*)message;
- (void)saveSize;

@end

MessageSizeCaluclator.m

#import "Message.h"
#import "MessageSizeCaluclator.h"


@interface MessageSizeCaluclator () <UIWebViewDelegate>

@property (strong, nonatomic) Message* message;
@property (strong, nonatomic) UIWebView* webView;

@end


@implementation MessageSizeCaluclator

@synthesize message = _message;
@synthesize webView = _webView;


- (id)initWithMessage:(Message*)message
{
self = [super init];

if (self) {
    _message = message;

    // WebView
    _webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 10, 10)];
    _webView.delegate = self;
}

return self;
}

- (void)saveSize
{
NSLog(@"%s message = %@", __PRETTY_FUNCTION__, _message.text);

[_webView loadHTMLString:[NSString stringWithFormat:@"<div style='font-family:Helvetica;font-size:13px;'>This is a test</div>", _message.text]
                                 baseURL:nil];
}

#pragma mark - Web view delegate

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
NSLog(@"%s", __PRETTY_FUNCTION__);
}

- (void)webViewDidStartLoad:(UIWebView *)webView
{
NSLog(@"%s", __PRETTY_FUNCTION__);
}

- (void)webViewDidFinishLoad:(UIWebView *)webView
{
NSLog(@"%s", __PRETTY_FUNCTION__);
}

@end

Implementation

    MessageSizeCaluclator* messageSizeCalculator = [[MessageSizeCaluclator alloc] initWithMessage:message];
    [messageSizeCalculator saveSize];
like image 402
Hans One Avatar asked Apr 26 '13 14:04

Hans One


1 Answers

Add your UIWebView to some UIView, make its frame offscreen (so users can't see it). The delegate methods won't be called if UIWebView is not in the view hierarchy of the app.

like image 172
Vladimir Obrizan Avatar answered Oct 07 '22 19:10

Vladimir Obrizan