1

我有一个 WebView 的问题。我正在将 Html 字符串加载到 Web 视图中。作为基本 URL,我需要使用我的站点 URL(因为 html 中有一些相对链接,我无法修改它)。问题是我还需要使用一些存储在应用程序包中的图像和 css。因此,我正在使用此代码创建对本地资源的引用(结果字符串在 html 文件中用作 src):

NSString *cssUrl = [NSString stringWithString:@"file:"]; 
cssUrl = [cssUrl stringByAppendingString:[[NSBundle mainBundle] resourcePath]];
cssUrl = [cssUrl stringByAppendingString:@"/story.css"];

然后我还添加了:

cssUrl = [cssUrl stringByReplacingOccurrencesOfString:@"/" withString:@"//"];
cssUrl = [cssUrl stringByReplacingOccurrencesOfString:@" " withString:@"%20"];

知道如何解决问题以及如何创建对可在 Web 视图中使用的文件的引用吗?谢谢

弗朗切斯科

4

3 回答 3

0

似乎我试图做的事情是不可能的。要使用捆绑资源,您必须将 Web 视图的基本 URL 设置为资源路径。感谢大家的帮助

弗朗切斯科

于 2012-06-25T16:27:16.207 回答
0

首先,将一个目录,例如一个名为 的目录,导入web到所有文件所在的项目中。确保在 Xcode 询问您时选择“为任何文件夹创建组引用”。

现在,您可以将初始字符串放入其中的文件后,像这样加载它web,例如index.html

NSString* path = [[NSBundle mainBundle] pathForResource:
   @"index" ofType:@"html" inDirectory:@"web"];
if (path) 
   [self.webView loadRequest:
     [NSURLRequest requestWithURL:[NSURL fileURLWithPath:path]]];

现在,您的字符串中的所有相对源 URL 都将按预期工作,包括<img><a>

于 2012-06-15T14:41:08.703 回答
0

这个怎么样?

NSString *resourcePath = [[NSBundle mainBundle] pathForResource:@"story" ofType:@"css"];
NSURL *url = [NSURL fileURLWithPath:resourcePath];
NSString *theMagicalURLString = [url absoluteString];
于 2012-06-15T15:37:46.860 回答