在 UIWebView 中使用 HTML 和本地图像

我有一个 UIWebView 在我的应用程序,我想用来显示一个图像,将链接到另一个网址。

我在吸毒

<img src="image.jpg" /> to load the image.

问题是图像不加载(即。即使它被作为资源添加到我的项目中,并被复制到捆绑包中,它仍然不能被找到。

我已经尝试使用 NSBundle 来获得图像的完整路径,并使用它,但它仍然没有显示在网络视图。

有什么想法吗?

119713 次浏览

使用相对路径或文件: 路径来引用图像不适用于 UIWebView。相反,您必须使用正确的 baseURL 将 HTML 加载到视图中:

NSString *path = [[NSBundle mainBundle] bundlePath];
NSURL *baseURL = [NSURL fileURLWithPath:path];
[webView loadHTMLString:htmlString baseURL:baseURL];

然后你可以像这样参考你的图片:

<img src="myimage.png">

(来自 重访 uiwebview)

我也遇到过类似的问题,但所有的建议都没有帮助。

然而,问题在于部署过程中的 * . png 本身。

用这个:

[webView loadHTMLString:htmlString baseURL:[[NSBundle mainBundle] bundleURL]];

我也遇到了这个问题。在我的例子中,我处理的一些图像不是本地化的,而另一些是——用多种语言。一个基本的 URL 没有为我获得本地化文件夹中的图像。我通过以下方法解决了这个问题:

// make sure you have the image name and extension (for demo purposes, I'm using "myImage" and "png" for the file "myImage.png", which may or may not be localized)
NSString *imageFileName = @"myImage";
NSString *imageFileExtension = @"png";


// load the path of the image in the main bundle (this gets the full local path to the image you need, including if it is localized and if you have a @2x version)
NSString *imagePath = [[NSBundle mainBundle] pathForResource:imageFileName ofType:imageFileExtension];


// generate the html tag for the image (don't forget to use file:// for local paths)
NSString *imgHTMLTag = [NSString stringWithFormat:@"<img src=\"file://%@\" />", imagePath];

然后,在加载内容时,在 UIWebView HTML 代码中使用 imgHTMLTag。

我希望这对遇到同样问题的人有所帮助。

在阅读了 iOS 6 Programming Cookbok 中的几个章节并开始学习 Objective-c 和 iOS 编程之后,我想补充一点,如果要从 习俗包中加载资源并在 web 视图中使用它,可以这样完成:

NSString *resourcesBundlePath = [[NSBundle mainBundle] pathForResource:@"Resources" ofType:@"bundle"];
NSBundle *resourcesBundle = [NSBundle bundleWithPath:resourcesBundlePath];
[self.outletWebView loadHTMLString:[html description] baseURL:[resourcesBundle bundleURL]];

然后,在 html 中,你可以使用“自定义”包作为你的基本路径来引用一个资源:

body {
background-image:url('img/myBg.png');
}

我针对 rss-feed (进入 RSSItems)的复杂解决方案(或教程)只适用于设备:

#define CACHE_DIR       [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject]


for (RSSItem *item in _dataSource) {


url = [NSURL URLWithString:[item link]];
request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"GET"];


[NSURLConnection sendAsynchronousRequest:request
queue:queue
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {


@autoreleasepool {


if (!error) {


NSString *html = [[NSString alloc] initWithData:data
encoding:NSWindowsCP1251StringEncoding];


{
NSError *error = nil;


HTMLParser *parser = [[HTMLParser alloc] initWithString:html error:&error];


if (error) {
NSLog(@"Error: %@", error);
return;
}


HTMLNode *bodyNode = [parser body];


NSArray *spanNodes = [bodyNode findChildTags:@"div"];


for (HTMLNode *spanNode in spanNodes) {
if ([[spanNode getAttributeNamed:@"class"] isEqualToString:@"page"]) {


NSString *absStr = [[response URL] absoluteString];
for (RSSItem *anItem in _dataSource)
if ([absStr isEqualToString:[anItem link]]){


NSArray *spanNodes = [bodyNode findChildTags:@"img"];
for (HTMLNode *spanNode in spanNodes){
NSString *imgUrl = [spanNode getAttributeNamed:@"src"];
if (imgUrl){
[anItem setImage:imgUrl];
break;
}
}


[anItem setHtml:[spanNode rawContents]];
[self subProcessRSSItem:anItem];
}
}
}


[parser release];
}


if (error) {
NSLog(@"Error: %@", error);
return;
}


[[NSNotificationCenter defaultCenter] postNotificationName:notification_updateDatasource
object:self
userInfo:nil];


}else
NSLog(@"Error",[error userInfo]);
}
}];

还有

- (void)subProcessRSSItem:(RSSItem*)item{


NSString *html = [item html];
if (html) {


html = [html stringByReplacingOccurrencesOfString:@"<div class=\"clear\"></div>"
withString:@""];


html = [html stringByReplacingOccurrencesOfString:@"<p class=\"link\">"
withString:@""];


html = [html stringByReplacingOccurrencesOfString:@"<div class=\"page\">"
withString:@""];


html = [html stringByReplacingOccurrencesOfString:@"</div>"
withString:@""];


NSArray *array1 = [html componentsSeparatedByString:@"<a"];
if ([array1 count]==2) {
NSArray *array2 = [html componentsSeparatedByString:@"a>"];


html = [[array1 objectAtIndex:0] stringByAppendingString:[array2 objectAtIndex:1]];
}


NSURL *url;
NSString *fileName;
NSString *filePath;
BOOL success;
if ([item image]) {


url = [NSURL URLWithString:
[hostString stringByAppendingString:[item image]]];
NSData *imageData = [NSData dataWithContentsOfURL:url];


fileName = [[[url relativePath] componentsSeparatedByString:@"/"] lastObject];


filePath = [NSString stringWithFormat:@"%@/%@",
CACHE_DIR,
fileName];


//save image locally
success = [[NSFileManager defaultManager] createFileAtPath:filePath
contents:imageData
attributes:nil];


//replace links
html = [html stringByReplacingOccurrencesOfString:[item image]
withString:filePath];


[item setImage:fileName];


//Передадим обновление интерфейса, снабдив индексом обновляемой ячейки
[[NSNotificationCenter defaultCenter] postNotificationName:notification_updateRow
object:self
userInfo:[NSDictionary dictionaryWithObject:@([_dataSource indexOfObject:item])
forKey:@"row"]];
}


//finalize html
html = [NSString stringWithFormat:@"<html><body>%@</body></html>",html];


fileName = [[[item link] componentsSeparatedByString:@"/"] lastObject];
filePath = [NSString stringWithFormat:@"%@/%@",
CACHE_DIR,
fileName];
success = [[NSFileManager defaultManager] createFileAtPath:filePath
contents:[html dataUsingEncoding:NSUTF8StringEncoding]
attributes:nil];


[item setHtml:
(success)?filePath:nil];//for direct download in other case
}

}

视图控制器

- (void)viewDidAppear:(BOOL)animated{


RSSItem *item = [[DataSingleton sharedSingleton] selectedRSSItem];


NSString* htmlString = [NSString stringWithContentsOfFile:[item html]
encoding:NSUTF8StringEncoding error:nil];
NSURL *baseURL = [NSURL URLWithString:CACHE_DIR];


[_webView loadHTMLString:htmlString
baseURL:baseURL];

}

RSS 项目类

#import <Foundation/Foundation.h>


@interface RSSItem : NSObject


@property(nonatomic,retain) NSString *title;
@property(nonatomic,retain) NSString *link;
@property(nonatomic,retain) NSString *guid;
@property(nonatomic,retain) NSString *category;
@property(nonatomic,retain) NSString *description;
@property(nonatomic,retain) NSString *pubDate;
@property(nonatomic,retain) NSString *html;
@property(nonatomic,retain) NSString *image;
@end

任何带有图像的 html 的一部分

<html><body>
<h2>blah-blahTC One Tab 7</h2>
<p>blah-blah НТС One.</p>
<p><img width="600" height="412" alt="" src="/Users/wins/Library/Application Support/iPhone Simulator/5.0/Applications/2EAD8889-6482-48D4-80A7-9CCFD567123B/Library/Caches/htc-one-tab-7-concept-1(1).jpg"><br><br>
blah-blah (Hasan Kaymak) blah-blah HTC One Tab 7, blah-blah HTC One. <br><br>
blah-blah
microSD.<br><br>
blah-blah Wi-Fi to 4G LTE.</p>
</p>
</body></html>

保存为名称 Htc-one-tab-7-eption-1(1) . jpg的图像

如果你使用图像的相对链接,那么图像将不会显示,因为在 iOS 应用程序编译之后,所有的文件夹结构都不会被保留。你所能做的就是通过添加“ 。捆绑”文件扩展名将你的本地网络 文件夹转换成一个 捆绑

因此,如果你本地网站是包含在一个文件夹“ Www”,这应该被重命名为“ 第一季,第12集”。这允许保留图像文件夹和目录结构。然后将‘ Html’文件以 HTML 字符串的形式加载到 WebView 中,并将‘ BaseURL’(设置为 www.bundle path)以便能够加载相关的图像链接。

NSString *mainBundlePath = [[NSBundle mainBundle] resourcePath];
NSString *wwwBundlePath = [mainBundlePath stringByAppendingPathComponent:@"www.bundle"];
NSBundle *wwwBundle = [NSBundle bundleWithPath:wwwBundlePath];
if (wwwBundle != nil) {
NSURL *baseURL = [NSURL fileURLWithPath:[wwwBundle bundlePath]];
NSError *error = nil;
NSString *page = [[NSBundle mainBundle] pathForResource:@"index.html" ofType:nil];
NSString *pageSource = [NSString stringWithContentsOfFile:page encoding:NSUTF8StringEncoding error:&error];
[self.webView loadHTMLString:pageSource baseURL:baseURL];
}

您可以通过选择 < em > 将文件添加到“ MyProj” 并选择 创建文件夹引用向您的项目添加文件夹(比如带有子文件夹 css、 img 和 js 以及文件 test.html 的 WEB)。现在,下面的代码将处理所有引用的图像、 css 和 javascript

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"WEB/test.html" ofType:nil];
[webView  loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:filePath]]];

这些答案确实对我有所帮助——特别是文件: xxxxxx.xxx,但是我必须做一个变通来显示图像。

在我的例子中,我的服务器上有一个 HTML 文件,我将其下载到 document 目录。我想它显示在一个 UIWebView 的本地图形,我不能得到的工作。我是这么做的:

  1. 将文件从 NSBundle 复制到本地文档目录
  2. 将 HTML 文档中的文件引用为“ file: filename.png”

因此,在启动时,将文件复制到文档目录:

-(BOOL)copyBundleFilesToDocumentsDirectoryForFileName:(NSString *)fileNameToCopy OverwriteExisting:(BOOL)overwrite {
//GET DOCUMENTS DIR
//Search for standard documents using NSSearchPathForDirectoriesInDomains
//First Param = Searching the documents directory
//Second Param = Searching the Users directory and not the System
//Expand any tildes and identify home directories.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];


//COPY FILE FROM NSBUNDLE File to Local Documents Dir
NSString *writableFilePath = [documentsDir  stringByAppendingPathComponent:fileNameToCopy];


NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *fileError;


DDLogVerbose(@"File Copy From Bundle to Documents Dir would go to this path: %@", writableFilePath);


if ([fileManager fileExistsAtPath:writableFilePath]) {
DDLogVerbose(@"File %@ already exists in Documents Dir", fileNameToCopy);


if (overwrite) {
[fileManager removeItemAtPath:writableFilePath error:nil];
DDLogVerbose(@"OLD File %@ was Deleted from  Documents Dir Successfully", fileNameToCopy);
} else {
return (NO);
}
}


NSArray *fileNameParts = [fileNameToCopy componentsSeparatedByString:@"."];
NSString *bundlePath = [[NSBundle mainBundle]pathForResource:[fileNameParts objectAtIndex:0] ofType:[fileNameParts objectAtIndex:1]];
BOOL success = [fileManager copyItemAtPath:bundlePath toPath:writableFilePath error:&fileError];


if (success) {
DDLogVerbose(@"Copied %@ from Bundle to Documents Dir Successfully", fileNameToCopy);
} else {
DDLogError(@"File %@ could NOT be copied from bundle to Documents Dir due to error %@!!", fileNameToCopy, fileError);
}


return (success);
}

尝试使用 base64图像字符串。

NSData* data = UIImageJPEGRepresentation(image, 1.0f);


NSString *strEncoded = [data base64Encoding];


<img src='data:image/png;base64,%@ '/>,strEncoded

立陶宛电视台的回答:

webView.loadHTMLString(htmlString, baseURL: NSBundle.mainBundle().bundleURL)

目标 C 答案:

let logoImageURL = NSURL(fileURLWithPath: "\(Bundle.main.bundlePath)/PDF_HeaderImage.png")

雨燕3:

webView.loadHTMLString("<img src=\"myImg.jpg\">", baseURL: Bundle.main.bundleURL)

这对我来说是有效的,即使图像在文件夹中没有任何修改。