Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIWebView and Richtext files

As far as I understand, the standard UIWebView is able to display local files of numerous extensions. Since I need to display formatted text in my application, I thought this method is the way to go.

So, I created a rich text file, called test.rtf, and I am currently trying to display it in my webview. However, I am unsuccessful. I see only a blank white screen instead of the text I typed into the rtf file.

Can someone look at my code and point out where I went wrong with the implementation?

Header file:

#import <UIKit/UIKit.h>
@interface MainViewController : UIViewController <UIWebViewDelegate> {
UIWebView * webView;
}
@end

Main file:

#import "MainViewController.h"
@interface MainViewController ()
@end
@implementation MainViewController

- (id)init
{
self = [super init];
if (self) {
    // Customization at initialization
    self.view.backgroundColor = [UIColor clearColor];

    //Adding a webview to display richtext documents
    int webHeight = self.view.bounds.size.height;
    webView = [[UIWebView alloc] initWithFrame:CGRectMake(0.0, 150.0, 320.0, webHeight-150.0)];
    webView.dataDetectorTypes = NO;
    webView.scrollView.bounces = NO;
    webView.delegate = self;
    [webView setBackgroundColor:[UIColor clearColor]];
    [webView setOpaque: NO];
    [self.view addSubview:webView];
    }
return self;
}

- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.

// Accessing richtext file
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"rtf"];
NSURL *url = [NSURL fileURLWithPath:filePath];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
if (request) {
    // Additional configuration
}

//Adding the content of the webiew
[webView loadRequest:request];
}

- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
  • (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType { NSLog(@"delegate called"); // Do whatever you want here return YES; } @end
like image 574
Gergely Kovacs Avatar asked Jan 19 '26 06:01

Gergely Kovacs


1 Answers

You should set your UIWebView's delegate and return YES. UIWebViewDelegate Protocol Reference says:

webView:shouldStartLoadWithRequest:navigationType:

Sent before a web view begins loading a frame.

So you should return YES for the first time to load your test.rtf file.

As you have updated your question. You need to set

webView.delegate = self;
//webView.delegate = appDelegate;    // not this line
like image 67
sunkehappy Avatar answered Jan 20 '26 18:01

sunkehappy