UIWebView - Load a local .html file with linked resources

一曲冷凌霜 提交于 2019-12-12 12:11:58

问题


I don't know how many forums I have already read, but I really don't know why it doesn't work!

I have an iPhone Application and I would like to show a Epub book to my user.

The user can read it online, otherwise he can download it into the Application Documents directory to read it afterwards.

I build this folder structure same like the online version and saved it into the document folder "frontend".

I ALSO can read this maintaine .HTML file, BUT the linked JS / CSS and HTML files does not work.

So I have some screenshots. I don't know, why the javascript cannot access to the .html docs.

offline version - saved into the filesystem "document folder"

online version - directly from server - it's ok!

I hope you could give me some hints.


回答1:


Simply write the code

NSString *path = [[NSBundle mainBundle] pathForResource:@"offlineEpub" ofType:@"html"];
NSString *content = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
UIWebView *webView = [[UIWebView alloc] init];
[webView loadHTMLString:content baseURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]]];
[self.view addSubview:webView];

The main thing is provide base url as your mainBundle or documents directory.




回答2:


After much fiddling around and reading a lot of answers, here is my simple consolidated solution:

1) Make sure all your bundle resources are unique---directories get flattened

It is super frustrating, but if you had directories "About/index.html" and "Home/index.html", one of the last "index.html" to get copied into the bundle will overwrite the previous.

2) JavaScript files will be in the wrong Build Phase

In Xcode click on your project, then click on your app target, then click on Build Phases. Notice the JavaScript files will wrongly be in Compiled Sources: move JS files into Copy Bundle Resources.

3) Use UIWebView's loadRequest:

Don't load from a string. Use an NSURL instead.

NSBundle *mainBundle = [NSBundle mainBundle];
NSURL *url = [mainBundle URLForResource:@"some_page" withExtension:@"html"];
NSURLRequest *urlReq = [NSURLRequest requestWithURL:url];

// Assuming you create an IBOutlet defined like:
// @property (strong, nonatomic) IBOutlet UIWebView *wv;
[self.wv loadRequest:urlReq];


来源:https://stackoverflow.com/questions/13289589/uiwebview-load-a-local-html-file-with-linked-resources

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!