Использование HTML и локальных изображений внутри UIWebView
У меня есть UIWebView в моем приложении, которое я хочу использовать для отображения изображения, которое будет ссылаться на другой URL.
Я использую
<img src="image.jpg" /> to load the image.
Проблема заключается в том, что изображение не загружается (т.е. оно не может быть найдено), даже если оно добавлено как ресурс в моем проекте и скопировано в пакет.
Я попытался использовать NSBundle, чтобы получить полный путь к изображению и использовать его, и он по-прежнему не отображается в веб-представлении.
Любые идеи?
Ответы
Ответ 1
Использование относительных путей или файла: пути к обращению к изображениям не работают с UIWebView. Вместо этого вам нужно загрузить HTML в представление с помощью правильного baseURL:
NSString *path = [[NSBundle mainBundle] bundlePath];
NSURL *baseURL = [NSURL fileURLWithPath:path];
[webView loadHTMLString:htmlString baseURL:baseURL];
Затем вы можете обратиться к своим изображениям следующим образом:
<img src="myimage.png">
(из uiwebview revisited)
Ответ 2
Используйте это:
[webView loadHTMLString:htmlString baseURL:[[NSBundle mainBundle] bundleURL]];
Ответ 3
Я тоже столкнулся с этой проблемой. В моем случае я имел дело с некоторыми изображениями, которые не были локализованы, а другие - на нескольких языках. Базовый 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];
Затем используйте imgHTMLTag в коде HTML UIWebView при загрузке содержимого.
Я надеюсь, что это поможет любому, кто столкнулся с той же проблемой.
Ответ 4
У меня была близкая проблема, но все предложения не помогли.
Однако проблема заключалась в самой *.png. У него не было альфа-канала. Как-то Xcode игнорирует все png файлы без альфа-канала во время процесса развертывания.
Ответ 5
Вы можете добавить в свой проект папку (например, WEB с подпапками css, img и js и файл test.html), выбрав Добавить файлы в "MyProj" и выбрав Создать ссылки на папку. Теперь следующий код позаботится обо всех упомянутых изображениях, css и javascript
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"WEB/test.html" ofType:nil];
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:filePath]]];
Ответ 6
попробуйте использовать строку изображения base64.
NSData* data = UIImageJPEGRepresentation(image, 1.0f);
NSString *strEncoded = [data base64Encoding];
<img src='data:image/png;base64,%@ '/>,strEncoded
Ответ 7
После того, как я прочитал пару глав в iOS 6 Programming Cookbok и начал изучать программирование objective-c и iOS, я хотел бы добавить, что если вы собираетесь загружать ресурсы из пользовательского пакета и использовать его в веб-представление, оно может быть выполнено следующим образом:
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');
}
Ответ 8
В Swift 3:
webView.loadHTMLString("<img src=\"myImg.jpg\">", baseURL: Bundle.main.bundleURL)
Это работало для меня, даже когда изображение находилось внутри папки без каких-либо изменений.
Ответ 9
Если вы используете относительные ссылки на изображения, изображения не будут отображаться, поскольку все структуры папок не будут сохранены после компиляции приложения iOS. То, что вы можете сделать, - это преобразовать вашу локальную веб-папку в пакет, добавив расширение расширения .bundle.
Итак, если ваш локальный веб-сайт содержится в папке " www", это должно быть переименовано в " www.bundle". Это позволяет сохранить папки изображений и структуру каталогов. Затем загрузите файл index.html 'в WebView в виде строки HTML с baseURL' (установите путь к www.bundle), чтобы включить загрузку ссылок относительного изображения.
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];
}
Ответ 10
Эти ответы помогли мне - в частности, файл:\\xxxxxxx.xxx, но мне пришлось сделать обходной путь для отображения изображения.
В моем случае у меня есть файл HTML на моем сервере, который я загружаю в каталог документов. Я хочу, чтобы он отображался с локальной графикой в UIWebView, с которой я не мог работать. Вот что я сделал:
- Скопируйте файл из NSBundle в каталог локальных документов
- Ссылка на файл в моем документе HTML как "файл:\\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);
}
Ответ 11
Быстрая версия ответа Lithu T.V:
webView.loadHTMLString(htmlString, baseURL: NSBundle.mainBundle().bundleURL)
Ответ 12
Быстрая версия Адама Александерса Задача C:
let logoImageURL = NSURL(fileURLWithPath: "\(Bundle.main.bundlePath)/PDF_HeaderImage.png")
Ответ 13
Мое комплексное решение (или учебник) для 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-concept-1 (1).jpg