如何在UIWebview中使用SDWebImage

时间:2014-01-25 20:09:32

标签: ios ios7 uiwebview sdwebimage

就像我们使用UIImageview

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 ...}];

有没有办法在SDWebImage代码

中的UIWebview中使用<img>
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];

提前致谢:)

1 个答案:

答案 0 :(得分:0)

首先缓存您的图片:

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"];
    }
  }];

然后当你需要图像时

__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
   }
  }];

然后在你的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]]];

在缓存图片时你不必使用密钥,我只是觉得它让事情变得容易一点。