将 UIWebView 根 URL 重新映射到 [[NSBundle mainBundle] bundleURL] [英] Remap UIWebView root URL to [[NSBundle mainBundle] bundleURL]
问题描述
我的 iPhone 应用程序中有一些 HTML 和一些图像,排列如下:
I've got some HTML and some images in my iPhone app, arranged something like:
html/
foo.html
images/
bar.png
我可以通过几种不同的方式让 bar.png
出现在我的 UIWebView
中——要么从 foo.html
code>NSUrl,然后从 html 目录返回目录树:
I can get bar.png
to appear in my UIWebView
a couple of different ways -- either loading foo.html
from an NSUrl
, and walking back up the directory tree from the html directory:
<img src="../images/bar.png"/>
或通过将 foo.html
加载到字符串中,使用 loadHtmlString
,并使用 [[NSBundle mainBundle] bundleURL]
作为 >baseURL
:
or by loading foo.html
into a string, using loadHtmlString
, and using [[NSBundle mainBundle] bundleURL]
as the baseURL
:
<img src="images/bar.png"/>
虽然这两种方法都有些笨拙——在第一种情况下,如果我移动 HTML 文件,我必须重新调整所有相对路径,而在第二种情况下,我必须忽略实际的路径结构HTML 文件.
Both of these are kind of clumsy, though -- in the first case, if I move HTML files around I have to rejigger all the relative paths, and in the second case, I have to ignore the actual path structure of the HTML files.
我想做的是这个 --
<img src="/images/bar.png"/>
-- 将 bundleURL
视为站点"的根.有什么办法可以使这项工作正常进行,还是我注定要将其转换为 file:///images/bar.png
并且找不到文件?
-- treating the bundleURL
as the root of the "site". Is there any way to make this work, or am I doomed to have that translated into file:///images/bar.png
and have the file not found?
推荐答案
如果我没记错的话,您的项目包中有一些文件要加载到 Web 视图中.您只需使用以下几行代码即可完成:
If I'm not mistaken, you have some files in your project bundle that you want to load in your web view. You can do it simply with these few lines of code:
NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"bar" ofType:@"png"];
NSURL *imageURL = [NSURL fileURLWithPath:imagePath];
我假设您有一个包含 Web 视图模式的文本/html 文件.您需要将图像作为对象添加到那里 (src="%@"...
),然后将 imageURL
添加到模式:
I'm assuming that you have a text/html file containing the pattern for your web view. You'll need to add the image as an object there (src="%@"...
) and then add the imageURL
to the pattern:
NSString *path = [[NSString alloc]initWithString:[[NSBundle mainBundle]pathForResource:@"htmlPattern" ofType:@"html"]];
NSError *error;
NSString *pattern = [[NSString alloc]initWithContentsOfFile:path
encoding:NSUTF8StringEncoding
error:&error];
htmlPage = [[NSString alloc]initWithFormat:pattern,
imageURL;
webView = [[UIWebView alloc] initWithFrame:WEBVIEW_FRAME];
[webView loadHTMLString:htmlPage baseURL:[NSURL URLWithString:path]];
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:pattern]]];
这篇关于将 UIWebView 根 URL 重新映射到 [[NSBundle mainBundle] bundleURL]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!