I am using SDWebImage to get image from url. I want to get the size of remote image in order to do some layout calculation. Since I only know the url of the image, how can I get it from SDWebImage object?
please try this one, Its may be work for you
-(UIImage *)downloadImageAsync:(NSString *)imageKey
{
NSLog(#"image key : %#",imageKey);
__block UIImage *returnedImage;
SDWebImageManager *manager = [SDWebImageManager sharedManager];
[manager downloadWithURL:[NSURL URLWithString:imageKey] options:0 progress:^(NSUInteger receivedSize, long long expectedSize){
NSLog(#"received size %d expected size %lld", receivedSize, expectedSize);
}completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType,BOOL finished){
if(image && finished) {
returnedImage = image;
}
}];
if(returnedImage == nil) {
NSLog(#"Returned Image Nil");
}
return returnedImage;
}
Related
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.
I am using setImageWithURL:placeholderImage:options:andResize:withContentMode:success: method of SDWebImage. When I provide it with correct URL, pointing to picture, it works well. But when I feed it some non-picture URL (e.g. http://www.yandex.ru), SDWebImage does nothing, even success and failure blocks are not called.
How should I detect if SDWebImage would not get image from the URL specified?
Try to update SDWebImage to newest version and use new function instead of old:
sd_setImageWithURL:(NSURL *)url completed:(SDWebImageCompletionBlock)completedBlock
I'd recommend using the SDWebImageManager instead:
SDWebImageManager *manager = [SDWebImageManager sharedManager];
[manager downloadWithURL:imageURL
options:0
progress:^(NSInteger receivedSize, NSInteger expectedSize)
{
// progression tracking code
}
completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished)
{
if (image)
{
// do something with image
}
}];
And then check the error value in the completed block.
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.
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.
I have saved image data to core data, the key is binary data format. After I saved to the core data, I displaying the image in a UIImageView using valueForKey: . But After I launch the simulator again, everything is still saved, but the image data is gone, when I NSLog the key's data description, it's null.
NSDictionary *show = [NSJSONSerialization JSONObjectWithData:responseObject options:kNilOptions error:nil];
Summary *summary = [NSEntityDescription insertNewObjectForEntityForName:#"Summary" inManagedObjectContext:weakSelf.managedObjectContext];
summary.title = show[#"title"];
summary.poster = show[#"images"][#"poster"];
SDWebImageManager *manager = [SDWebImageManager sharedManager];
[manager downloadWithURL:[NSURL URLWithString:summary.poster] options:SDWebImageProgressiveDownload progress:^(NSUInteger receivedSize, long long expectedSize) {
} completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished) {
NSData *data = UIImageJPEGRepresentation(image, 0.5);
summary.posterImageData = data;
}];
[weakSelf.managedObjectContext dct_saveWithCompletionHandler:^(BOOL success, NSError *error) {
if (success) {
} else {
NSLog(#"%#", error);
}
}];
I think your current code, the downloadWithURL's completed block is being called after dct_saveWithCompletionHandler , try:
SDWebImageManager *manager = [SDWebImageManager sharedManager];
[manager downloadWithURL:[NSURL URLWithString:summary.poster] options:SDWebImageProgressiveDownload progress:^(NSUInteger receivedSize, long long expectedSize) {
} completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished) {
NSData *data = UIImageJPEGRepresentation(image, 0.5);
summary.posterImageData = data;
[weakSelf.managedObjectContext dct_saveWithCompletionHandler:^(BOOL success, NSError *error) {
if (success) {
} else {
NSLog(#"%#", error);
}
}];
}];
Make sure that you're actually saving the managed object context. Doublecheck that you've set the concurrency type for your MOCs correctly, too.