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

标签 html ios objective-c

我有 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/

相关文章:

iphone - 如何添加 uiimagepickerview 自定义覆盖

objective-c - 调整内部 View 添加/替换的窗口大小(OSX、Cocoa)?

javascript - contenteditable - JQuery 将内容仅保存到网页(以及添加和删除)

html - 匹配不连续且嵌套在一起的 Div 高度

html - 当元素包含长文本时,如何强制伪 "after"元素的宽度?

ios - AFHTTPRequestOperation 同步请求

ios - self.window.rootViewController.presentedViewController返回nil

html - 如何提取html内容?我有一个HTML页面。如何提取定义标签内的数据并将其打印在 o/p 文件中。???

iphone - ARC 在 iOS 4.3 中不工作

ios - 有没有办法使用我的 ios 应用程序将图像发布到 google+ 墙上?