oon*_*noo 19 iphone resources uiwebview
问候!任何人都可以请我帮忙找到解决方法:
我已经看过如何使用baseURL在应用程序包/ MainBundle中加载的教程,这很简单但不能使用iPhone的Documents目录中的资源.
我的文件夹的结构如下:
dirX
|---> file.xml
|---> dirCSS
|---> style.css
Run Code Online (Sandbox Code Playgroud)
我可以检索目录X的完整路径(Users /......./ dir X).但是,当将该路径传递给UIWebView的baseURL时
[webView loadHTMLString:fileXMLString baseURL:pathToDirX]
Run Code Online (Sandbox Code Playgroud)
... webView无法识别资源(例如dirCSS中的style.css)作为fileXMLString中的href'
<link href="dirCSS/style.css" rel="stylesheet" />
Run Code Online (Sandbox Code Playgroud)
所以目前我的应用程序可以成功加载html字符串但不加载样式表,因为html字符串中CSS的链接是相对的 - 例如.CSS/style.css文件
很感谢任何形式的帮助 :)
oon*_*noo 25
经过一些谷歌搜索,我终于找到了一个适合我提出的问题的解决方案.希望这可以帮助那些面临同样问题的人.
诀窍在于为UIWebView的baseURL创建NSURL对象时格式化字符串路径.虽然在大多数情况下我通常使用典型的"Users /...../dir/file",但使用UIWebView的loadHTMLString:baseURL加载需要不同的方法.
如http://dblog.com.au/iphone-development/loading-local-files-into-uiwebview/中所述,我得到了解决方案,资源的字符串路径只需要用双线程替换斜线%20的斜杠和空格:
NSString *imagePath = [[NSBundle mainBundle] resourcePath];
imagePath = [imagePath stringByReplacingOccurrencesOfString:@"/" withString:@"//"];
imagePath = [imagePath stringByReplacingOccurrencesOfString:@" " withString:@"%20"];
NSString *HTMLData = @"
<h1>Hello this is a test</h1>
<img src="sample.jpg" alt="" width="100" height="100" />";
[webView loadHTMLString:HTMLData baseURL:
[NSURL URLWithString:
[NSString stringWithFormat:@"file:/%@//",imagePath]
]];
Run Code Online (Sandbox Code Playgroud)
请注意更换琴弦以及:
[NSString stringWithFormat:@"file:/%@//",imagePath]
Run Code Online (Sandbox Code Playgroud)
虽然上面的示例代码是检索应用程序的mainBundle的路径,但它也可以在我的其他文件夹中工作,即Documents(及其子文件夹).
亲切的问候,oonoo
PS再次感谢Nic的回复:)
小智 12
要获取文档目录的路径:
NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory, NSUserDomainMask ,YES );
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"index.xml"];
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:path]]]
Run Code Online (Sandbox Code Playgroud)
让一切正常运行的最简单方法是从文档目录中加载index.html而不是加载字符串.否则将baseUrl设置为文档目录.