繁体   English   中英

如何从本地文件加载时替换从html img src加载图像

[英]how to replace loading image from html img src on loading it from local file

我有HTML代码。 我想从中预加载图像并保存在本地文件中。 我将HTML转换为NSAttributedString并在UITextView中显示该字符串。

NSAttributedString *htmlAttributedText =
        [[NSAttributedString alloc] initWithData:[htmlText dataUsingEncoding:NSUTF16StringEncoding]
                                        options:@{ NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType }
                              documentAttributes:nil
                                           error:&err];

textView.attributedText = htmlAttributedText;

如何从本地文件而不是从Internet加载图像?

下面的代码将列出HTML中的图像数组。 获取所有图像的列表

NSMutableArray * arrayToStoreImages = [[NSMutableArray alloc] init];
NSRegularExpression* imageRegex = [[NSRegularExpression alloc] initWithPattern:@"<img[^>]*>" options:0 error:NULL] ;
[imageRegex enumerateMatchesInString:HTMLBODY options:0 range:NSMakeRange(0, [HTMLBODY length]) usingBlock:^(NSTextCheckingResult *match, NSMatchingFlags flags, BOOL *stop){

[arrayToStoreImages 
addObject:NSStringFromRange(match.range)];           
}];

使用SDWebImage下载所有图像,并使用HASH从获取的URL中使用名称将其存储到本地存储中。 将实际的URL替换为本地哈希路径。 将HTML转换为NSAttributedString并从本地存储中删除图像,因为它是临时的。

如果图像由SDWebImage缓存,它将从缓存中传递,否则将下载新的图像。

如果我理解正确,那么对我而言,使用SDWebImage的最简单,最快的方法

在您下载完图片后,请保存为lib,下次尝试从同一url下载图片时,lib将为您提供缓存的图片。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM