How to use SDWebImage in UIWebview - ios

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.

Related

Download image using SDWebImage, error -999 (or) SDWebImageErrorDomain Code=0 "Downloaded image has 0 pixels

I am unable to download the image in Objective c Using SDWebImage 4.4.5 version., I tried the following , nothing worked.
Try 1:
[self.thumbnailImageView sd_setImageWithURL:[NSURL URLWithString:thumbnailURLString] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
}];
Try 2:
[self.thumbnailImageView sd_setImageWithURL:[NSURL URLWithString:thumbnailURLString] placeholderImage:nil options:SDWebImageRefreshCached completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) { if(image != nil){
self.thumbnailImageView.image = image;
} else {
NSLog(#"Photo Not Available, fetch");
[self.thumbnailImageView sd_setImageWithURL:[NSURL URLWithString:thumbnailURLString] placeholderImage:nil options:SDWebImageRefreshCached completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
if(image != nil) { NSLog(#"Lo Res Image Loaded by %ld from '%#'", (long)cacheType, imageURL);
self.thumbnailImageView.image = image;
} else {
self.thumbnailImageView.image = nil;
} }];
} }];
Try 3:
[[SDWebImageDownloader sharedDownloader] downloadImageWithURL:[NSURL URLWithString:thumbnailURLString] options:SDWebImageDownloaderUseNSURLCache progress:nil completed:^(UIImage *image, NSData *data, NSError *error, BOOL finished) {
}];
Try 4:
SDWebImageManager *manager = [SDWebImageManager sharedManager];
[manager loadImageWithURL:[NSURL URLWithString:thumbnailURLString] options:SDWebImageDelayPlaceholder progress:^(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL) {
} completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, SDImageCacheType cacheType, BOOL finished, NSURL * _Nullable imageURL) {
}];
Try 5:
SDWebImageDownloader *manager = [SDWebImageManager sharedManager].imageDownloader;
[manager setValue:#"application/vnd.learning.events.v1+json" forHTTPHeaderField:#"Accept"];
[manager setValue:#"en-US" forHTTPHeaderField:#"Accept-Language"];
[manager setValue:#"application/json; charset=utf-8" forHTTPHeaderField:#"Content-Type"];
//[manager setValue:savedEmail forHTTPHeaderField:#"Email"];
[manager setValue:savedToken forHTTPHeaderField:#"Authorization"];
[manager downloadImageWithURL:[NSURL URLWithString:thumbnailURLString] options:SDWebImageDownloaderHighPriority progress:^(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL) {
} completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, BOOL finished) {
self.thumbnailImageView.image = image;
}];
In all the above cases, getting the following error:
Error Domain=NSURLErrorDomain Code=-999 "cancelled" UserInfo={NSErrorFailingURLStringKey=https://thisisnotcorrecturl.net/api/BAImage?ActionFlagId=97&id=615, NSErrorFailingURLKey=https://thisisnotcorrecturl.net/api/BAImage?ActionFlagId=97&id=615, _NSURLErrorRelatedURLSessionTaskErrorKey=(
"LocalDataTask <92586538-B07D-46FB-8694-3B29AA3F0CB4>.<7>"
), _NSURLErrorFailingURLSessionTaskErrorKey=LocalDataTask <92586538-B07D-46FB-8694-3B29AA3F0CB4>.<7>, NSLocalizedDescription=cancelled}
Earlier, we used v3.5.4 version used, able to download the image with the following code. It's working good.
[self.thumbnailImageView setImageWithURL:[NSURL URLWithString:thumbnailURLString]
placeholderImage:nil
completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType) {
if (image != nil){
self.thumbnailImageView.image = [self imageResizingToAspetRatio:image];
}
}];
Kindly let me know if did any mistake, or any suggestions.
Update 1:
Tried to download the image using post man. Kindly check the image.
The same image URL is working on SDWebImage v3.5.4 after i upgraded to SDWebImage v4.4.5, it is not lodging the image.
Is there any configurations am i missing? Installed pod 'SDWebImage/WebP' also, added SD_WEBP=1 in Build settings -> Preprocessor macros.
Error: Error Domain=SDWebImageErrorDomain Code=0 "Downloaded image has 0 pixels" UserInfo={NSLocalizedDescription=Downloaded image has 0 pixels}
http://testingurl.net/api/Image?ActionFlagId=20&id=864
Authorization:
Email: kkk1#ler.com ,
Token: A-BE3D-WER3-847F-ER6YG5678G
Basically, SDWebImage has no issue for downloading them from any URL if the URL contains an image.
But in your case, you have tried to get an image from JSON. Your server API returns a JSON object that contains the image as base64String. When you get the JSON response then you need to get the base64String from json and then create an image from the base64String.
You can use this method for decoding string to image using Objective C.
- (UIImage *)decodeBase64ToImage:(NSString *)strEncodeData {
NSData *data = [[NSData alloc]initWithBase64EncodedString:strEncodeData options:NSDataBase64DecodingIgnoreUnknownCharacters];
return [UIImage imageWithData:data];
}
First, update pod and try SDWebImage pod version 3.8.2.
And the second thing is to check your image URL. because I personally test image download with this pod version and downloading functionality is working.
I faced the same issue and I was trying webP images. I realised later that I need to add webP coder to SDImageCodersManager. Something like
SDImageCodersManager.shared.addCoder(SDImageWebPCoder.shared)
I did this in AppDelegate.
If you are suffering such type issue from SDWebImage library you can go with other one as well which are supporting base64 string object
One of best library I found is "Kingfisher"
Hope you like this and it will solve your issue.

iphone 7+ image not loading from image url

This is my code image are loading on all other devices but on iPhone 7+ its blank is their any bug or any correction I need to implement
[activityOnImage startAnimating];
NSString *strUrl = [[NSString stringWithFormat:#"%#",useFullLinkObj.imageUrl]stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
[videoImage ecs_setImageWithURL:[NSURL URLWithString:strUrl] placeholderImage:nil options:0 completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
[activityOnImage stopAnimating];
}];

How to convert images of gif picture to NSData for iOS?

In my iOS Application, I want to show a Gif image in my tableViewCell. Download this Gif image by SDWebImage, and use FLAnimatedImageView to show this image.
But now I have a problem, SDWebImage return a images ,but the FLAnimatedImageView want a NSData.
How to convert images of gif to NSData?
Forgive my poor English.
[[SDWebImageManager sharedManager] downloadImageWithURL:url options:0 progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
if (image.images.count > 0)//gif
{
// how to get the data
FLAnimatedImage *animatedImage = [FLAnimatedImage animatedImageWithGIFData:data];
_chatGIFImage.animatedImage = animatedImage1;
}
}];
If you have the URL of the image you can directly use the following to convert it to NSData
NSData *data = [NSData dataWithContentsOfURL: imageURL];
You can do something like below:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSError* error = nil;
NSData* ImageData = [NSData dataWithContentsOfURL:yourIMGUrl options:NSDataReadingUncached error:&error];
if (error) {
NSLog(#"%#", [error localizedDescription]);
} else {
NSLog(#"successfull.");
dispatch_sync(dispatch_get_main_queue(), ^{
FLAnimatedImage *animatedImage = [FLAnimatedImage animatedImageWithGIFData:ImageData];
_chatGIFImage.animatedImage = animatedImage1;
});
}
});
You can simply use
// UIImageJPEGRepresentation(<#UIImage * _Nonnull image#>, <#CGFloat compressionQuality#>)
NSData *data = UIImageJPEGRepresentation(image, 1.0);
Compression quality can be between 0.0 (high compression, low quality) and 1.0 (low compression, high quality)

images from foursquare are NSURLErrorFileDoesNotExist = -1100

I am attempting to download an image from foursquare( sourced from using the venue api) and I keep getting NSURLErrorFileDoesNotExist = -1100, errors for trying to grab the image.
imageUrl = [NSURL URLWithString: [NSString stringWithFormat:
[#"https://irs0.4sqi.net/img/general/720x400/1203715_jAVNrPE87IFuOUa69i1q5UXQ0bUAfjG8V-R_hBUL09c.jpg" stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
//[cell.venueImageView sd_setImageWithURL:imageUrl placeholderImage:nil];
typeof(WHMDateListTableViewCell *) __weak weakCell = cell;
[cell.venueImageView sd_setImageWithURL:imageUrl placeholderImage:[UIImage imageNamed:#"create-profile-step-4-pic-box-reg"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
weakCell.venueImageView.image = image;
}];
The image url loads fine in Chrome. I have also pulled other images from other web urls and it works fine.
The issue was that the API was returning images with an https scheme. Once I manipulated the returned URL to be of http, instead of https then I was able to properly download the image for imageview display.
//setup Venue
NSURL *imageUrl;
imageUrl = [NSURL URLWithString:self.selectedDate.Venue.Media[indexPath.item]];
NSURLComponents *components = [NSURLComponents new];
components.scheme = #"http";
components.host = imageUrl.host;
components.path = imageUrl.path;
NSURL *url = [components URL];
[cell.photoImageView sd_setImageWithURL:url placeholderImage:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
;
}];

SDWebImageManager image not loaded into TableViewController

I am using SDWebImageImagemanger to hadnle asyn call and caching. However it does not return the image to the cell.imageview.view. Here is the code:
NSString *imageURLString=[[tableData objectAtIndex:indexPath.row] valueForKey:#"picture"];
NSURL *url = [NSURL URLWithString:imageURLString];
SDWebImageManager *manager = [SDWebImageManager sharedManager];
[manager downloadWithURL:url
options:0
progress:^(NSInteger receivedSize, NSInteger expectedSize)
{
// progression tracking code
}
completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished)
{
if (image)
{
cell.imageView.image = image;
}
}];
You should use it this way:
NSString* imageURL = [[tableData objectAtIndex:indexPath.row] valueForKey:#"picture"];
[cell.imageView setImageWithURL:[NSURL URLWithString:imageURL]];
For that, first import the category:
#import <SDWebImage/UIImageView+WebCache.h>
Please note that you don't use the manager at all, you just use the UIImageView+WebCache category provided by the library, which gives you the setImageWithURL: method. There are other variants of the method which allows you to keep track of the download process, a completion handler, etc.

Resources