在UIWebView中使用HTML和本地图像
我的应用程序中有一个UIWebView,我想用它来显示链接到另一个url的图像 我正在使用在UIWebView中使用HTML和本地图像,html,ios,iphone,uiwebview,uikit,Html,Ios,Iphone,Uiwebview,Uikit,我的应用程序中有一个UIWebView,我想用它来显示链接到另一个url的图像 我正在使用 <img src="image.jpg" /> to load the image. 加载图像。 问题是,即使图像作为资源添加到我的项目中并复制到捆绑包中,它也无法加载(即找不到) 我尝试使用NSBundle获取图像的完整路径,但它仍然没有显示在web视图中 有什么想法吗?使用相对路径或文件:引用图像的路径不适用于UIWebView。相反,您必须使用正确的baseURL将HTML加载到视图
<img src="image.jpg" /> to load the image.
加载图像。
问题是,即使图像作为资源添加到我的项目中并复制到捆绑包中,它也无法加载(即找不到)
我尝试使用NSBundle获取图像的完整路径,但它仍然没有显示在web视图中
有什么想法吗?使用相对路径或文件:引用图像的路径不适用于UIWebView。相反,您必须使用正确的baseURL将HTML加载到视图中:
NSString *path = [[NSBundle mainBundle] bundlePath];
NSURL *baseURL = [NSURL fileURLWithPath:path];
[webView loadHTMLString:htmlString baseURL:baseURL];
然后,您可以像这样参考您的图像:
<img src="myimage.png">
NSString *resourcesBundlePath = [[NSBundle mainBundle] pathForResource:@"Resources" ofType:@"bundle"];
NSBundle *resourcesBundle = [NSBundle bundleWithPath:resourcesBundlePath];
[self.outletWebView loadHTMLString:[html description] baseURL:[resourcesBundle bundleURL]];
(from)我有一个类似的问题,但所有的建议都没有帮助 然而,问题在于*.png本身它没有阿尔法通道。在部署过程中,Xcode会忽略所有没有alpha通道的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];
//确保您有图像名称和扩展名(出于演示目的,我对文件“myImage.png”使用了“myImage”和“png”,这可能是本地化的,也可能不是本地化的)
NSString*imageFileName=@“myImage”;
NSString*imageFileExtension=@“png”;
//在主捆绑包中加载映像的路径(这将获得所需映像的完整本地路径,包括它是否本地化以及是否有@2x版本)
NSString*imagePath=[[NSBundle mainBundle]pathForResource:imageFileName类型:imageFileExtension];
//为图像生成html标记(不要忘记将file://用于本地路径)
NSString*imgHTMLTag=[NSString stringWithFormat:@',imagePath];
然后,在加载内容时,在UIWebView HTML代码中使用imgHTMLTag
我希望这能帮助任何遇到同样问题的人。在阅读了iOS 6编程指南中的几章并开始学习objective-c和iOS编程之后,我想补充一点,如果要从自定义包加载资源并在web视图中使用,可以这样完成:
<img src="myimage.png">
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提要(进入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]);
}
}];
及
}
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
#导入
@接口RSSItem:NSObject
@属性(非原子,保留)NSString*标题;
@属性(非原子,保留)NSString*链接;
@属性(非原子,保留)NSString*guid;
@属性(非原子,保留)NSString*类别;
@属性(非原子,保留)NSString*说明;
@属性(非原子,保留)NSString*pubDate;
@属性(非原子,保留)NSString*html;
@属性(非原子,保留)NSString*图像;
@结束
任何带有图像的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>
一个标签7
胡说八道
诸如此类(Hasan Kaymak)诸如此类的HTC一号标签7,诸如此类的HTC一号
废话
microSD.
胡说八道的Wi-Fi到4G LTE
为名称保存的图像htc-one-tab-7-concept-1(1)。jpg如果使用图像的相对链接,则图像不会显示,因为在iOS应用程序编译后,所有文件夹结构都不会保留。您可以通过添加“.bundle”文件扩展名将本地web文件夹转换为捆绑包 因此,如果您的本地网站包含在文件夹“www”中,则应将其重命名为“www.bundle”。这样可以保留图像文件夹和目录结构。然后将“index.html”文件作为带有“baseURL”(设置为www.bundle path)的html字符串加载到WebView中,以启用加载相对图像链接
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];
}
通过选择将文件添加到“MyProj”并选择创建文件夹引用,您可以将文件夹(例如带有子文件夹css、img和js的WEB以及file test.html)添加到项目中。现在,下面的代码将处理所有引用的图像、css和javascript
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"WEB/test.html" ofType:nil];
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:filePath]]];
这些答案确实对我有所帮助——特别是文件:\\xxxxxxx.xxx,但我必须做一些变通来显示图像 在我的例子中,我的服务器上有一个HTML文件,我将其下载到documents目录。我希望它在UIWebView中显示本地图形,但我无法使用它。以下是我所做的:
-(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
NSData*data=UIImageJPEG表示法(图像,1.0f);
NSString*strEncoded=[data BASE64编码];
,强度编码
利图电视台答案的Swift版本:
webView.loadHTMLString(htmlString, baseURL: NSBundle.mainBundle().bundleURL)
Adam Alexanders的Swift版本目标C答案:
let logoImageURL = NSURL(fileURLWithPath: "\(Bundle.main.bundlePath)/PDF_HeaderImage.png")
在Swift 3中:
webView.loadHTMLString("<img src=\"myImg.jpg\">", baseURL: Bundle.main.bundleURL)
webView.loadHTMLString(“,baseURL:Bundle.main.bundleURL)
即使图像未经任何修改就放在文件夹中,这对我来说也是有效的。从iPhone OS 3.0开始,我就无法再这样做了:((StackOverflow.com).为什么投票被否决?:/他们不一定是邪恶的。也许他们有正当的理由?我们可能永远也不知道。如果他们能有礼貌地在评论中解释他们为什么投票被否决……就必须在投票被否决时写评论。@Jasarien:我需要同样的功能。但我不明白在ht中应该通过什么在[webView loadHTMLString:htmlString baseURL:baseURL]中的mlString以及我如何在html中放置我的图像。[[NSBundle mainBundle]bundleURL]我们可以将其用作bundleURL这对我来说所做的就是在我的webView中给我一个字符串