我有 HTML 代码。我想从中预加载图像并保存在本地文件中。我将 HTML 转换为 NSAttributedString 并在 UITextView 中显示该字符串。
NSAttributedString *htmlAttributedText =
[[NSAttributedString alloc] initWithData:[htmlText dataUsingEncoding:NSUTF16StringEncoding]
options:@{ NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType }
documentAttributes:nil
error:&err];
textView.attributedText = htmlAttributedText;
如何从本地文件加载图片而不是从互联网加载?
最佳答案
下面的代码将列出 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 下载所有图像,并使用从获取的 URL 中使用 HASH 的名称将其存储到本地存储。 将实际 URL 替换为本地 HASH 路径。 将 HTML 转换为 NSAttributedString 并从本地存储中删除临时图像。
如果图像由 SDWebImage 缓存,它将从缓存中传递,否则它将下载新的图像。
关于html - 如何在从本地文件加载图像时替换从 html img src 加载图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29389683/