Loading images from Images.xcassets - ios

I am trying to load more than 100 images from the bundle, however recently I was just curious what is the best practice to load the images dynamically from the bundle. Will custom Images.xcassets allow me to do such task? How can I dynamically load NSArray?

To start with my answer I will recommend, DON'T do it.
Its really an overkill for your app to load 100 images and to store them in memory, at once, and the app would definitely go under some memory pressure.
In Xcode 5, .xcassets is still the best place to keep your images in app bundle. For further details you might be interested in Apple Asset Catalog documentation. However, rather than loading and storing images to NSArray, I would recommend you to store their identifiers (actually the image names as added to .xcassets) in the array. Also it would be helpful if you store the image identifiers to some NSString* const beforehand.
So your coding structure should look something like the following:
//image names
NSString* const kImage1 = #"image1";
NSString* const kImage2 = #"image2";
NSString* const kImage3 = #"image3";
//...etc
NSArray* imageIdentifiers = #[kImage1, kImage2, kImage3,...];
//...
And then to load individual image from bundle you could use:
UIImage* img = [UIImage imageNamed:kImage3]; //loads image3 from bundle and caches
Or to traverse through all images you might use:
for (NSString* identifier in imageIdentifiers) {
#autoreleasepool { //make sure your image data gets disposed after use
UIImage* img = [UIImage imageNamed:identifier];
//... use img, etc.
}
}
And finally, imageNamed: method of UIImage class, caches an image in system cache. So you won't have to worry about reloading it from file, if you reuse one.

Related

Is there a way to refresh the cache used by UIImage class?

In my iOS app I am using the +imageNamed: method to load an image (many times and in many different places in the code).
In one case the user might update (download) a new image.
When I try to load the new, it will show the old, due to caching.
From the "Is there a way to clear the cache used by UIImage class?" question, I saw that I have to use the -initWithContentsOfFile: method.
But this will not take advantage of the caching speedup that the +imageNamed: enjoys. All I want is to "tell" the cache that the file has changed, so it needs to "re-cache" it. And then keep using the +imageNamed: method with the new cached image.
In other words, I use the +imageNamed: method (say) 10 times, I change the image, I "tell" the cache, then I continue use the +imageNamed: method another (say) 10 times. If I change all the +imageNamed: to -initWithContentsOfFile: then I lose the caching advantage.
Is there a way/trick to do that?
There is no API for clearing the cache. If your app is not destined for the app store you could call the private method:
[UIImage _flushSharedImageCache];
However I wouldn't want this anywhere near production code.
Instead I would create a category on UIImage and add a method for returning the desired image from a filename. This name would be stored and then updated when your new image is downloaded. You will get the benefit of caching, without any hacky workarounds.
Depending on the complexity of your project, a simple find and replace shouldn't take too long.
Although I'm now questioning how your app is working currently, imageNamed only looks for files in your app's bundle, so won't work for images downloaded by the user.
You'll probably just have to figure out your own way of caching your images.
I'd suggest using a UIImage category with a static NSMutableDictionary that can hold your cached images. Then just use your custom caching method when initialising your UIImage.
For example:
#interface UIImage (UIImageCache)
+(UIImage*) cachedImageFile:(NSString*)imageFile;
+(void) resetCacheForImageFile:(NSString*)imageFile;
#end
#implementation UIImage (UIImageCache)
static NSMutableDictionary* cachedImages;
+(UIImage*) cachedImageFile:(NSString*)imageFile {
// Optional error checking
NSAssert1([[NSFileManager defaultManager] fileExistsAtPath:imageFile], #"Warning! The image file %# doesn't exist.", imageFile);
if (!cachedImages) cachedImages = [NSMutableDictionary dictionary];
UIImage* cachedImg = [cachedImages objectForKey:imageFile];
if (cachedImg) return cachedImg; // Image is cached, return it
else { // No cached image, create one
UIImage* img = [UIImage imageWithContentsOfFile:imageFile]; // iOS won't auto-cache the image.
[cachedImages setObject:img forKey:imageFile];
return img;
}
}
+(void) resetCacheForImageFile:(NSString*)imageFile {
[cachedImages removeObjectForKey:imageFile];
}
#end
Maybe I just got late to the party...but using
+ (UIImage *)imageWithContentsOfFile:(NSString *
I got rid of the cache issue.
Hope it helps!!

iOS8 extension : share images between container and extension

I'm making an iOS 8 extension. Here's what I'm trying to do: Users select images from the photo library in the container app, and these images will be shared with the extension and for the further use.
Right now I'm doing it in this way (If you don't want to read this part, please skip below to read the actual codes): Use App Group and NSUserDefaults to share datas. Convert UIImage into NSData and then save all the images in a NSArray, then save the array into a NSDictionary (I have many arrays and this is the way I organize them - so I have to save them into dictionary), finally save the dictionary into user default.
Here's the coding:
NSArray *imageArray = ...
//this array contains all the images.
//photoDataArray is a NSMutableArray;
photoDataArray = [[NSMutableArray alloc]init];
for (UIImage *images in imageArray) {
[photoDataArray addObject:UIImagePNGRepresentation(images)];
}
NSThread * creationThread = [[NSThread alloc] initWithTarget:self selector:#selector(handleData) object:nil];
[creationThread start];
-(void)handleData{
NSDictionary *dic = [[NSDictionary alloc]init];
[dic SetObject:photoDataArray forKey:#"testImageArray"];
NSUserDefaults * def = [[NSUserDefaults alloc] initWithSuiteName:#"group.myCompany.myApp"];
[def setObject:dic forKey:#"dataDic"];
//done with saving data
[self.navigationController popViewControllerAnimated:YES];
//Navigation
}
When I want to retrieve the images:
NSUserDefaults * def = [[NSUserDefaults alloc] initWithSuiteName:#"group.myCompany.myApp"];
NSDictionary *dic = [def ObjectForKey:#"dataDic"];
NSArray *dataArray = [dic objectForKey:#"testImageArray"];
NSMutableArray *convertedArray = [[NSMutableArray alloc] init];
for (NSData *imageData in dataArray) {
[convertedArray addObject:[UIImage imageWithData:imageData]];
}
convertedArray would be the array of images I want to get.
Apparently, there are a lot of problems if I do it this way.
For example, the two major issues:
Doing this takes a lot of resources including memory. It takes about half minute to actually finish the process.If I have a array with about 20 images, I'll get "didRecieveMemoryWarning" about 3 times (I'm using a iPad mini as a test device). Sometimes the datas are not saved correctly. After the viewController is popped out(which means it runs to the last line of my storing code), I get nil for the array I just saved into the UserDefault! I'm sure my coding all worked normal, and this issue is caused by low memory because if the array has less than 15 images, I can save and retrieve them perfectly.
It's hard to save new images into a previously saved array. When I want to do that, I have to retrieve the previous array and add new image datas into that array, and then save the new array into the UserDefault. As mentioned before, saving an array into the UserDefault takes a lot of memory.
So my questions are pretty straight foward and specific:
Are there any other ways to transfer images from one target to another? In other words: How can I transfer images from the container app to the extension?
If not, are there any ways to solve the issue in my codes? Is this a proper way to do it?
Those are all I want to ask, but if you could answer following questions for me also, it will be really nice:
Why would I get more than one "didRecieveMemoryWarning" in one saving process? When the system received memory warning, will it stop the action immediately?
(Just to make sure) Is that safe to use UIImagePNGRepresentation for all the images including PNG and JPG?
Thank you.
From Apple's Documentation on App Extension Programming
Sharing Data with Your Containing App
The security domains for an app extension and its containing app are distinct, even though the extension bundle is nested within the containing app’s bundle. By default, your extension and its containing app have no direct access to each other’s containers.
You can, however, enable data sharing. For example, you might want to allow your app extension and its containing app to share a single large set of data, such as prerendered assets.
.....
When you set up a shared container, the containing app—and each contained app extension that you allow to participate in data sharing—have read and write access to the shared container. To avoid data corruption, you must synchronize data accesses. Use Core Data, SQLite, or Posix locks to help coordinate data access in a shared container.

PhotoKit iOS8 - Retrieve image using the "PHImageFileURLKey"

Is there anyway I can use the Path returned from the "PHImageFileURLKey" to go into the photo library and retrieve the image?
The path returned is in this format:
"file:///var/mobile/Media/DCIM/102APPLE/IMG_2607.JPG"
My plan is to store this path in the database and use it to fetch the image when I need to get it back.
Any help is appreciated. Thank you!
I think your solution of retrieving Photo Kit asset from the URL is wrong.
Here is what I would do (supposing you have access to PHAsset):
Store the localIdentifier:
PHAsset *asset = /*Your asset */
NSString *localIdentifier = asset.localIdentifier;
//Now save this local identifier, or an array of them
When it is time to retrieve them you simply do:
PHFetchResult *savedAssets = [PHAsset fetchAssetsWithLocalIdentifiers:savedLocalIdentifiers options:nil];
[savedAssets enumerateObjectsUsingBlock:^(PHAsset *asset, NSUInteger idx, BOOL *stop) {
//this gets called for every asset from its localIdentifier you saved
}];
If you only have access to “PHImageFileURLKey” then disregard this answer.
This isn't documented, so I'd strongly advise against using that URL for anything more than a prototype app. That said, this does appear to work:
dispatch_queue_t queue = dispatch_queue_create("photoLoadQueue", 0);
dispatch_async(queue, ^{
NSURL *privateUrl = [NSURL URLWithString:#"file:///var/mobile/Media/DCIM/102APPLE/IMG_2607.JPG";
NSData *imageData = [NSData dataWithContentsOfURL:privateUrl];
dispatch_async(dispatch_get_main_queue(), ^{
self.imageView.image = [UIImage imageWithData:imageData];
});
});
Naturally you'll need to replace the string used to initiate the url with one which is valid for your phone.
There are probably a load of issues with doing this - it's just not how the framework is meant to be used. Here are some off the top of my head:
When running in the simulator, the root path changes regularly between launches of the app, so if you store absoluteUrls like this your database will quickly become full of dead URLs. This will be inconvenient to say the least.
Worse, the URLs for the images may change on a real device - you don't have control over it, and once they change it's your app's fault for making the user reselect them or whatever.
You're not going to ever find out about changes to the PHAsset which the photo came from.
This may be circumventing user permission for photo access - what happens if your app's permission to access photos is revoked? This is probably an issue with lots of approaches to storing photos for later use, however.
You don't control the file - what if the user deletes it?
If I were you, I would retrieve the image properly from the photos framework, using PHImageManager requestImageForAsset: targetSize: contentMode: options: resultHandler:, and store it in a file within your app's directory, at a sensible resolution for whatever you're doing with it. This still doesn't give you asset changes, but is a pretty good solution.
If you want to store the assets themselves and only request the images when you actually need them, it might be worth investigating transient asset collections, though I've not used them so that might not work for what you need.

Get unique Image file path in application Directory (Cache) w.r.t unique URL of images stored at server in SDWEBIMAGE

I am using SDWEBIMAGE library for show images in ImageView in my app.
I am stuck in find unique file path of stored image in cache by SDWEBIMAGE. I need a file path of particular Image w.r.t it's URL in cached images in Document Directory of app.
So, imagepath must be unique for every URL.
I was go through this This Discussion link But no luck.
Any help will be appreciated.
From the documentation:
To lookup the cache, you use the queryDiskCacheForKey:done: method. If
the method returns nil, it means the cache doesn't currently own the
image. You are thus responsible for generating and caching it. The
cache key is an application unique identifier for the image to cache.
It is generally the absolute URL of the image.
SDImageCache *imageCache = [[SDImageCache alloc] initWithNamespace:#"myNamespace"];
[imageCache queryDiskCacheForKey:myCacheKey done:^(UIImage *image)
{
// image is not nil if image was found
}];
UPDATE
You can get the path to your image like this:
NSString *myImgKey;//this is the key for the image you want the path for
[[SDImageCache sharedImageCache] defaultCachePathForKey:myImgKey];
in case you do not use the default location, you can use:
- (NSString *)cachePathForKey:(NSString *)key inPath:(NSString *)path;
This function returns the path for a certain key, but you will have to pass it your cache's root folder.
SDwebImage always encrypt your image name. But if you want to access the image you can use your URL as the key to read the image from SDWebImage (- (UIImage *)imageFromDiskCacheForKey:(NSString *)key;). See the SDWebImageCache.
https://github.com/rs/SDWebImage/blob/master/SDWebImage/SDImageCache.h
Still if you want to access the path you can create the category of SDWebImageCache and use private method
(NSString *)defaultCachePathForKey:(NSString *)key
See - How to get filesystem path to image cached with SDWebImage (iOS)

UIImages NSURLs and Threads

I am trying to build a nice function to access the network for images, if they are found on the web, I store them in a cache system I made.
If the image was already stored on the cache, I return it.
The function is called getImageFromCache and returns an image if it is in the cache, else, it would go to the network and fetch.
The code might look like this:
UIImageView* backgroundTiles = [[UIImageView alloc] initWithImage[self getImageFromCache:#"http://www.example.com/1.jpg"]];
Now, I am moving on to using threads because of big latencies due to network traffic. So I want images to show a temp image before I get the result from the web.
What I want to know is how can I keep track of so many images being accessed sequentially, being added to UIImageViews by this function (getImageFromCache).
Something just won't work there:
-(UIImage*)getImageFromCache:(NSString*)forURL{
__block NSError* error = nil;
__block NSData *imageData;
__block UIImage* tmpImage;
if(forURL==nil) return nil;
if(![self.imagesCache objectForKey:forURL])
{
// Setting a temporary image until we start getting results
tmpImage = [UIImage imageNamed:#"noimage.png"];
NSURL *imageURL = [NSURL URLWithString:forURL];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
imageData = [NSData dataWithContentsOfURL:imageURL options:NSDataReadingUncached error:&error];
if(imageData)
{
NSLog(#"Thread fetching image URL:%#",imageURL);
dispatch_async(dispatch_get_main_queue(), ^{
tmpImage = [UIImage imageWithData:imageData];
if(tmpImage)
{
[imagesCache setObject:tmpImage forKey:forURL];
}
else
// Couldn't build an image of this data, probably bad URL
[imagesCache setObject:[UIImage imageNamed:#"imageNotFound.png"] forKey:forURL];
});
}
else
// Couldn't build an image of this data, probably bad URL
[imagesCache setObject:[UIImage imageNamed:#"imageNotFound.png"] forKey:forURL];
});
}
else
return [imagesCache objectForKey:forURL];
return tmpImage;
}
This is not a direct answer to your question, but are you aware that there is no need to use GCD to download things asynchronously (on a background thread)? Just use NSURLConnection and its delegate methods. All your code will be on the main thread but the actual connection and downloading will happen in the background.
(And in fact I have written a class, MyDownloader, that takes care of all this for you:
http://www.apeth.com/iOSBook/ch37.html#_http_requests
Scroll down to the part about MyDownloader and its subclass MyImageDownloader, which is doing exactly the sort of thing you need done here. Moreover, note the subsequent code in that chapter showing how to use a notification when a download completes, prompting the table view that need these images to reload the row that contains the image view whose image has just arrived.)
its good your building it from scratch but if you want to save the all the work, there's a drop in Replacement SDWebImage Library with support for remote images coming from the web, and has all the functionality Like Temp Image, Asychronous Loading, Caching etc, you said you need
In your background thread, once the download has completed and you've saved the image to the cache, I'd suggest you post a notification using the NSNotificationCenter to let other parts of your app know that the cache has been updated.
This assumes that whichever part of the app manages the image views has registered its interest in those notification with the addObserverForName method. When it receives such a notification, it can then attempt to retrieve the images from the cache again and update its image views if appropriate.
Depending on the number of image views, you may want to pass through the image url in the notification in some way (e.g. in the userInfo dictionary), and then based on that decide which image views should be refreshed rather than refreshing them all.
I should add that I would also recommend getting rid of the inner dispatch_async call. There's no need for that, although you may need to add synchronisation to your cache object so it can be safely accessed from the main thread as well as the download thread.

Resources