简体   繁体   中英

How to use SDWebImage in UIWebview

Like we set image in UIImageview using SDWebImage

[imageview.setImageWithURL:[NSURL URLWithString:@"http://www.domain.com/path/to/image.jpg"]
               placeholderImage:[UIImage imageNamed:@"placeholder.png"]
                      completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType) {... completion code here ...}];

Is there any way to use SDWebImage in UIWebview in <img> tag

NSString *htmlString =@"<html lang=\"en\"><img src='http://cdn.tutsplus.com/mobile/uploads/legacy/iOS-SDK_UIView-Animation/Animate-Icon.png'   /> </div><div id=\"content\"><div>BlahBlahBlah LoremIpsum</div><br></body>"

[WebView loadHTMLString:descriptionHT baseURL:nil];

Thanks in advance :)

First cache your image:

SDWebImageManager *manager = [SDWebImageManager sharedManager];
  [manager downloadWithURL:[NSURL URLWithString:@"http://cdn.tutsplus.com/mobile/uploads/legacy/iOS-SDK_UIView-Animation/Animate-Icon.png"]
options:
  0 progress : ^(NSInteger receivedSize, NSInteger expectedSize) {
    // progression tracking code
  }
completed:
  ^(UIImage * image, NSError * error, SDImageCacheType cacheType, BOOL finished) {
    if (image && finished) {
      [[SDImageCache sharedImageCache] storeImage:image forKey:@"icon"];
    }
  }];

Then when you need the image

__block NSString *imageSource;
__block NSData *imageData = [NSData data];

SDImageCache *imageCache = [SDImageCache sharedImageCache];
[imageCache queryDiskCacheForKey:@"icon" done:^(UIImage * image, SDImageCacheType cacheType) {
imageData = UIImagePNGRepresentation(image);
   if (image) {
      imageSource = [NSString stringWithFormat:@"data:image/png;base64,%@", [imageData base64Encoding]];
   } else {
      //start download of image
   }
  }];

Then in your html:

NSString *htmlString = [NSString stringWithFormat:@"<html lang=\"en\"><img src=\"%@\"/> </div><div id=\"content\"><div>BlahBlahBlah LoremIpsum</div><br></body>", imageSource];

[WebView loadHTMLString:htmlString baseURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]]];

You don't have to use a key when caching the image, I just thought it made things a little easier.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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