本文主要是針對后臺返回數(shù)據(jù)是 html 標簽的數(shù)據(jù)加載
異步加載 html 標簽內(nèi)的 img 標簽掠手,給 img 標簽添加點擊事件
例如返回的數(shù)據(jù)格式如下
<div>
一谅阿、《望天門山》 作者:唐代李白 1蛮放、原文
天門中斷楚江開拍皮,碧水東流至此回。兩岸青山相對出贿堰,孤帆一bai片日邊來辙芍。 2、譯文
天門山從中間斷裂是楚江把它沖開羹与,碧水向東浩然奔流到這里折回故硅。
兩岸高聳的青山隔著長江相峙而立,江面上一葉孤舟像從日邊駛來纵搁。
<img
src="https://wx2.sinaimg.cn/large/006CHHsBly1gkxrs7785ej31402eoe84.jpg"
/>
</div>
或者
完整的 html 標簽數(shù)據(jù)
這些數(shù)據(jù)一般都是使用了富文本編輯器編輯的內(nèi)容吃衅,而且各種標簽樣式都有可能使用到,所以最好還是使用 WKWebView 來加載诡渴!
但是如果內(nèi)容含有 img 標簽的話就會等待所有的圖片加載完才會展示出整體的樣式捐晶,這樣比較影響體驗菲语。
所以應該考慮異步加載圖片,而不影響文字等標簽樣式的展示惑灵。
Demo下載
1.先將圖片鏈接中的 scheme 替換為自定義的 scheme
- (void)changeImageScheme {
self.htmlString = [self.htmlString stringByReplacingOccurrencesOfString:self.oriImageUrl withString:self.xxxCustomImageUrl];
}
2.在 html 標簽中添加函數(shù)
- (void)addJsScript {
NSString *htmlLab = @"</html>";
NSString *scriptLab1 = @"</script>";
NSString *jsFunctionString = @"function xxxGetAllImg() { return document.getElementsByTagName(\"img\"); }\
function xxxUpdateImage(url, imgData) { var list = Array.from(xxxGetAllImg()); for (let item of list) { if ((item.src == url)) { item.src = imgData; break; } } } ";
if (![self.htmlString containsString:htmlLab]) {
[self addHtmlLab];
}
if ([self.htmlString containsString:scriptLab1]) {
NSString *scriptString = [NSString stringWithFormat:@"%@%@",jsFunctionString,scriptLab1];
self.htmlString = [self.htmlString stringByReplacingOccurrencesOfString:scriptLab1 withString:scriptString];
}else {
NSString *scriptLab0 = @"<script>";
NSString *scriptString = [NSString stringWithFormat:@"%@%@%@%@",scriptLab0,jsFunctionString,scriptLab1,htmlLab];
self.htmlString = [self.htmlString stringByReplacingOccurrencesOfString:htmlLab withString:scriptString];
}
}
3.定義一個實現(xiàn) WKURLSchemeHandler 協(xié)議的類
@interface XXXCustomSchemeHanlder : NSObject <WKURLSchemeHandler>
@property (nonatomic, copy) NSString *oriImageUrl;
@property (nonatomic, copy) NSString *oriImageScheme;
@property (nonatomic, strong) UIImage *placeholderImage;
@property (nonatomic, copy) void(^updateImageBlock)(void);
@end
4.實現(xiàn)協(xié)議方法 用于攔截圖片加載
- (void)webView:(nonnull WKWebView *)webView startURLSchemeTask:(nonnull id<WKURLSchemeTask>)urlSchemeTask {
UIImage *image = self.placeholderImage;
NSData *data = UIImageJPEGRepresentation(image, 1.0);
NSURLResponse *response = [[NSURLResponse alloc] initWithURL:urlSchemeTask.request.URL MIMEType:@"image/jpeg" expectedContentLength:data.length textEncodingName:nil];
[urlSchemeTask didReceiveResponse:response];
[urlSchemeTask didReceiveData:data];
[urlSchemeTask didFinish];
if (self.updateImageBlock) {
self.updateImageBlock();
}
NSString *htmlImageUrlStr = [NSString stringWithFormat:@"%@",urlSchemeTask.request.URL];
NSString *dloadImageUrlStr = [htmlImageUrlStr stringByReplacingOccurrencesOfString:XXXCustomImageScheme withString:self.oriImageScheme];
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
[self readImageForKey:dloadImageUrlStr htmlImageUrlStr:htmlImageUrlStr webView:webView];
});
}
- (void)readImageForKey:(NSString *)dloadImageUrlStr htmlImageUrlStr:(NSString *)htmlImageUrlStr webView:(WKWebView *)webView {
__weak typeof(self) weakSelf = self;
NSURL *url = [NSURL URLWithString:dloadImageUrlStr];
[[SDWebImageManager sharedManager] loadImageWithURL:url options:SDWebImageRetryFailed progress:nil completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) {
if (image || data) {
NSData *imgData = data;
if (!imgData) {
imgData = UIImageJPEGRepresentation(image, 1);
}
dispatch_async(dispatch_get_main_queue(), ^{
[weakSelf callJsUpdateImage:webView imageData:imgData htmlImageUrlStr:htmlImageUrlStr];
});
}
if (error) {
}
}];
}
- (void)callJsUpdateImage:(WKWebView *)webView imageData:(NSData *)imageData htmlImageUrlStr:(NSString *)imageUrlString {
__weak typeof(self) weakSelf = self;
NSString *imageDataStr = [NSString stringWithFormat:@"data:image/png;base64,%@",[imageData base64EncodedString]];
NSString *func = [NSString stringWithFormat:@"xxxUpdateImage('%@','%@')",imageUrlString,imageDataStr];
[webView evaluateJavaScript:func completionHandler:^(id _Nullable response, NSError * _Nullable error) {
if (weakSelf.updateImageBlock && !error) {
weakSelf.updateImageBlock();
}
}];
}
5.初始化 WKWebView 并配置攔截信息
WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
XXXCustomSchemeHanlder *schemeHandler = XXXCustomSchemeHanlder.new;
schemeHandler.oriImageScheme = self.oriImageScheme;
schemeHandler.oriImageUrl = self.oriImageUrl;
schemeHandler.placeholderImage = self.placeholderImage;
__weak typeof(self) weakSelf = self;
schemeHandler.updateImageBlock = ^ {
[weakSelf updateHeight];
};
[config setURLSchemeHandler:schemeHandler forURLScheme:XXXCustomImageScheme];
WKWebView *webView = [[WKWebView alloc]initWithFrame:CGRectMake(0, 0, self.width, self.height) configuration:config];
6. 更新高度
- (void)updateHeight {
[self nowUpdateHeight];
[self delayUpdateHeight];
}
- (void)nowUpdateHeight {
__weak typeof(self) weakSelf = self;
[self.webView evaluateJavaScript:@"document.body.offsetHeight" completionHandler:^(id _Nullable result,NSError * _Nullable error) {
// 高度會有一點少 山上,手動補上 20
CGFloat height = [result floatValue] + 20.0;
weakSelf.webView.height = height;
weakSelf.height = height;
if (weakSelf.loadOverHeight) {
weakSelf.loadOverHeight(height);
}
}];
}
- (void)delayUpdateHeight {
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, DelayTime * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
[self nowUpdateHeight];
});
}