I’m using
pod 'SDWebImage'
To download images in my application, I found that all the images were downloaded in “/Library/Caches/com.bundlename.bundlename/com.alamofire.imagedownloader/fsCachedData” with some unique names.
My app has offline support and I have managed CoreData Entity for the image with file path(files are in library caches directory), As I Upload my images my server will respond with my S3 file URL to download.
As I (the user who upload file) have an image file already but SDWebImage did not know that. So it will download the file again.
Any suggestion what should I do to manage it without downloading the same image again? I can not keep local path in my database as my app has sync function with multiple devices.
Thanks
I think you could use SDImageCache for this purpose.
Sample code:
NSArray<NSString*> *urls = #"aws s3 url here";
[[SDImageCache sharedImageCache] diskImageExistsWithKey:urls[0] completion:^(BOOL isInCache) {
if ( isInCache ) {
[yourImage setImage:[[SDImageCache sharedImageCache] imageFromDiskCacheForKey:urls[0]]];
} else {
NSURL *url = [NSURL URLWithString:item.url];
[yourImage sd_setImageWithURL:url completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
[[SDImageCache sharedImageCache] storeImage:image forKey:urls[0] toDisk:YES completion:^{
}];
[yourImage setImage:image];
}];
}
}] ;
Related
I have an image which I'm loading in a UIWebView. I've set the scaleToFit as YES for webView. Still it doesn't scale to the screen of webView.
This is happening only when I'm running it on iOS 10.3.1. It work fine on older versions.
self.webView.scalesPageToFit = YES;
Have you placed any constraints on the image? It could be to do with the device size rather than the iOS version?
Just a thought, might be completely wrong...
May I ask why you load an image into a UIWebView in the first place?
I recommend using UIImageView whenever possible. With this, you can set it's "contentMode" to your preferred setting. If you need a way to load remote images, check out this really popular & easy to use library:
https://github.com/rs/SDWebImage
With the above library loading a remote image is as easy as this:
[[SDWebImageDownloader sharedDownloader] downloadImageWithURL:[NSURL URLWithString:iconURL] options:SDWebImageDownloaderHighPriority progress:^(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL) {
} completed:^(UIImage * _Nullable image, NSData * _Nullable data, NSError * _Nullable error, BOOL finished) {
dispatch_async(dispatch_get_main_queue(), ^{
[yourImageView setImage:image];
});
}];
I would like to ask on how to get the downloaded image after the SDWebImageManager downloaded it. I have only the code to download it via URL, here's what I got:
let manager: SDWebImageManager = SDWebImageManager.sharedManager()
manager.downloadImageWithURL(NSURL(string: feedDetails.thumbnail), options: [],
progress: {(receivedSize: Int, expectedSize: Int) -> Void in
print(receivedSize)
},
completed: {(image, error, cached, finished, url) -> Void in
self.feedImage.image = image
}
)
As far as I know (I just looked up the author's Git page) there is the following method to directly access an image which is stored inside the cache-
You can use the SDImageCache to store an image explicitly to the cache with the following code:
[[SDImageCache sharedImageCache] storeImage:myImage forKey:myCacheKey];
Where myImage is the image you want to store and myCacheKey is a unique identifier for the image.
After you stored an image to the cache and want to use that image, just do the following:
[[SDImageCache sharedImageCache] queryDiskCacheForKey:myCacheKey done:^(UIImage *image) {
// image is not nil if image was found
}];
This code is Objective-C code, you have to "convert" it to swift yourself.
I hope I could help you!
From the SDWebImageManager class the downloadImageWithURL: method
Downloads the image at the given URL if not present in cache or return
the cached version otherwise.
So if the image is present in cache you are already retrieving it with your code, instead of downloading from the web.
Thanks for answer #beeef but SDWebImage has been updated some part of code:
Save image:
[[SDWebImageDownloader sharedDownloader] downloadImageWithURL:[NSURL URLWithString:string] options:SDWebImageDownloaderUseNSURLCache progress:nil completed:^(UIImage *image, NSData *data, NSError *error, BOOL finished) {
if (image && finished) {
// Cache image to disk or memory
[[SDImageCache sharedImageCache] storeImage:image forKey:#"img_key" toDisk:YES completion:^{
//save
}];
}
}];
Get image from disk cache:
[[SDImageCache sharedImageCache] queryCacheOperationForKey:#"img_key" done:^(UIImage * _Nullable image, NSData * _Nullable data, SDImageCacheType cacheType) {
[self.imageV setImage: image];
}];
Anyway to handle or display UIImage with caching and with placeholder?
I have found one answer from stack exchange but it didnot work for me given below the link :
Best way to cache images on ios app?
Notes: I dont have any URL because i get image object of PHIMAGE asset library.
You can use SDWebImage
It is very simple to display and cache image.
[imageView sd_setImageWithURL:[NSURL URLWithString:#"http://www.image_url.com"]
placeholderImage:[UIImage imageNamed:#"placeholder.png"]];
You can use a very usefull library called SDWebImage
SDWebImage automagically cache all your images when you provide a valid URL with the sd_setImageWithURL. So the next time you call it, will use the cache system instead of re-download the image.
Example to implement in a UIImageView from their github:
// Here we use the new provided sd_setImageWithURL: method to load the web image
[cell.imageView sd_setImageWithURL:[NSURL URLWithString:#"http://www.domain.com/path/to/image.jpg"]
placeholderImage:[UIImage imageNamed:#"placeholder.png"]];
There was a problem of smoothing an all image while scroll the table but there is an issue of reload the cell not the caching problem i solved this issue.
I get an image one by one from local identifier which is provided by PHAsset framework and display that image into cell.
For reference Code:
PHFetchResult *savedAssets = [PHAsset fetchAssetsWithLocalIdentifiers:#[your local identifier] options:nil];
[savedAssets enumerateObjectsUsingBlock:^(PHAsset *asset, NSUInteger idx, BOOL *stop) {
//this gets called for every asset from its localIdentifier you saved
PHImageRequestOptions * imageRequestOptions = [[PHImageRequestOptions alloc] init];
imageRequestOptions.synchronous = YES;
imageRequestOptions.deliveryMode = PHImageRequestOptionsResizeModeFast;
[[PHImageManager defaultManager]requestImageForAsset:asset targetSize:CGSizeMake(50,50) contentMode:PHImageContentModeAspectFill options:imageRequestOptions resultHandler:^(UIImage * _Nullable result, NSDictionary * _Nullable info) {
NSLog(#"You get an image from result");
}];
}];
I have implemented an app extension for my application, but i am facing an issue when trying to load an image from a URL into an imageView.
I tried to use PAImageView and UIImageView but both with failure.
The code that i was using for PAImageView is the following:
[self.imageView setImageURL:[NSURL URLWithString:#"https://blabblaLogo.jpg"]];
self.userImageView.clipsToBounds = YES;
and tried to use SDWebImage for UIImageView with the following:
[self.imageView setImageWithURL:[NSURL URLWithString:url] placeholderImage:[UIImage imageNamed:#"default.png"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType) {
}];
and the image doesnt appear in both cases. Note that a default image from assets is displayed correctly without any issue.
Is it possible to load an image from a URL in an app Extension? and how can we achieve that?
Thank you.
Am using something like this and it's work good until this issues fixed
cell.avatar.image = [UIImage imageNamed:#"selection-box_emty.png"];
// Load the image with an GCD block executed in another thread
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:Arr[indexPath.row][#"avatar"]]];
if (data) {
UIImage *offersImage = [UIImage imageWithData:data];
if (offersImage) {
dispatch_async(dispatch_get_main_queue(), ^{
UIImage *offersImage = [UIImage imageWithData:data];
cell.avatar.image = offersImage;
});
}
}
});
I faced a similar problem, put breakpoints into into library and problem apparently was App Tranport Security. We need separate App Transport Security Settings for every extension we add
Try This in your Image url
If image url contain any space it will add %20 and work fine
[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
I'm using SDWebImage for a while caching all my images but now i want to have more than one cache to to group various types of images. For example three kind of caches with several images each, so in runtime i want to clear one of them or have different setMaxCacheAge
Example:
types images = car images is one type, motorcycle is another... airplanes other.. like this. After i store this images i want delete or clear cache only of the motorcycle images (one type)
Now I have this but is for every images cached:
SDImageCache * sDImageCache = [SDImageCache sharedImageCache];
[sDImageCache setMaxCacheAge:60*60*24];
...
SDImageCache *imageCache = [SDImageCache sharedImageCache];
[imageCache clearMemory];
[imageCache clearDisk];
[imageCache cleanDisk];
-
I saw this but is really that i want?
SDImageCache *imageCache = [[SDImageCache alloc] initWithNamespace:#"myNamespace"];
Using Asynchronous Image Caching Independently
Ok I figure out how to do...and I will share
First i removed all evidences of [SDWebImageManager sharedManager], because I want to do everything manually.
Then [SDWebImageDownloader sharedDownloader] to request new one and queryDiskCacheForKey (SDImageCache) to get local image (disk or memory)
How:
Create new imageCache with specific namespace
self.imageCache = [[SDImageCache alloc] initWithNamespace:#"nameSpaceImageCacheXPTO"];
[_imageCache setMaxCacheAge:oneHour * 3]; // 3 hours
Check if the image (key) is already in cache if not will request new one and save later
/////////
// * Prepar Key
/////////
NSString * key = url.absoluteString;
/////////
// * Get Local Image
/////////
[_imageCache queryDiskCacheForKey:key done:^(UIImage *image, SDImageCacheType cacheType) {
if (image) {
completedBlock(image,nil); // return block
}else{
/////////
// * Request Image
/////////
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[[SDWebImageDownloader sharedDownloader] downloadImageWithURL:url
options:SDWebImageProgressiveDownload
progress:^(NSInteger receivedSize, NSInteger expectedSize) {}
completed:^(UIImage *image, NSData *data, NSError *error, BOOL finished) {
if (finished && image){
/////////
// * Save Image
/////////
[_imageCacheProgram storeImage:image
recalculateFromImage:NO
imageData:data
forKey:key
toDisk:YES];
completedBlock(image,error); // return block
}
}];
});
}
}];