Load images from a documents subdirectory into UICollectionViewCell - ios

I have several images in png format in "/Documents/saved/" directory.
I loaded this directory into an array called "contents"
When i use NSLog to view the contents of this array, i see the images as well as a .DS_STORE file
What i want to do is load all these images into UICollectionView cells.
I tried this,
[[cell collectionImageView] setImage:
[UIImage imageWithContentsOfFile:
[contents objectAtIndex:indexPath.item]]];
The collectionImageView is connected to the UIImageView in the UICollectionViewCell
But it doesn't seem to work.EDIT
NSString *dataPath = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents/DImage"];
NSArray *contents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:dataPath error:NULL];
NSLog(#"%#", contents);
This gives me the output
2013-03-25 10:37:20.186 aUX[543:c07] (
".DS_Store",
"savedImage_0.png",
"savedImage_1.png",
"savedImage_2.png",
"savedImage_3.png",
"savedImage_4.png",
"savedImage_5.png"
)
(I have dragged a UIImageView named collectionImageView.)
I need to display these images one by one in the collection view cells.

It is not clear what data types you are using. Maybe breaking up your one-liner might help bring more clarity to the situation. Also, in this way you can check each step with NSLog or in the debugger.
NSString *fileName = [contents objectAtIndex:indexPath.item];
NSString *path = [filesDirectory stringByAppendingPathComponent:fileName];
UIImage *image = [UIImage imageWithContentsOfFile:path];
UIImageView *cellImageView = cell.collectionImageView;
cellImageView.image = image;
Maybe your contents array contains NSURLs rather than NSStrings. In this way you can find out.

in ur cellForRowAtIndexPath
cell.collectionImage.image=[contents objectAtIndex:indexPath.row];
return cell;

Related

My app doesn't show image on iOS 7

I have an app,that contains UIImageView. it's working on iOS 8 but not showing image on iOS 7. I searched it, they always said that "it's auto layout problem." ok i removed all constraints on my view. but still not showing images.
NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:sf._foto];
[Img setImage:[UIImage imageNamed:savedImagePath]];
Img.frame = CGRectMake(0,0,screenWidth,screenHeight);
Don't know if this will help but this is how I saved and then accessed an image through the documents directory
- (void)savePaystubToFile: (UIImage *)image {
if (image != nil)
{
NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString * documentsDirectory = [paths objectAtIndex:0];
NSString * path = [documentsDirectory stringByAppendingPathComponent: #"example.png" ];
NSData * data = UIImagePNGRepresentation(image);
[data writeToFile:path atomically:YES];
}
}
- (UIImage*)loadPaystub {
NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString * documentsDirectory = [paths objectAtIndex:0];
NSString * path = [documentsDirectory stringByAppendingPathComponent: #"example.png" ];
// If nothing is stored at that location then return nil
UIImage * image = [UIImage imageWithContentsOfFile:path] ? [UIImage imageWithContentsOfFile:path] : nil;
return image;
}
The main difference here seems to be me using the imageWithContentsOfFile function and the basic set up of the process step by step.
I don't know whether this is the issues which you are struggling with but this is a better way of separating the storage and retrieval of your image. If this is working correctly then you know that the problem will be in accessing the frame.
If you are finding it is an autolayout issue, then you will need to remove the view from your xib and add it programmatically. I've had similar issues and just creating it programmatically, even if that means creating another xib with your view and loading it and adding it to your view's addSubview:. Every view that I want to modify later, but don't want to deal with modifying constraints, I add programmatically.
Alternatively, you could add your constraints and then put outlets to them in your code to modify when you want to change things.
Hopefully this helps.

Image not showing in my UICollectionView

So I've been looking for a solution to this issue, but can't seem to find anything. I have an array that I load with image paths using the below method
- (IBAction)btnPictures:(id)sender {
// Create the next view controller.
ImageGalleryViewController *galleryViewController = [[ImageGalleryViewController alloc] initWithNibName:#"ImageGalleryViewController" bundle:nil];
// Search for paths and get users home directory
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
// get path at first index (in case multiple returned
NSString *documentsDirectory = [paths objectAtIndex:0];
NSArray *dirContents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:documentsDirectory error:nil];
NSArray *files = [dirContents filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:#"pathExtension IN %#", #"png"]];
// Pass the selected object to the new view controller.
[galleryViewController setImageArray:files];
// Push the view controller.
[self.navigationController pushViewController:galleryViewController animated:YES];
}
That image array is then sent to the below method in my UICollectionViewController
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
ImageGalleryViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:#"ImageGalleryViewCell" forIndexPath:indexPath];
NSLog(#"Image at index %#", [imageArray objectAtIndex:indexPath.row]);
[cell.galleryImage setImage:[UIImage imageWithContentsOfFile:[imageArray objectAtIndex:indexPath.row]]];
[cell setBackgroundColor:[UIColor whiteColor]];
return cell;
}
I verified the objectAtIndex is returning a valid image name through my NSLog, but for some reason the cell is not displaying it.
Any help is greatly appreciated, thanks in advance.
The array returned by -contentsOfDirectoryAtPath: of NSFileManager doesn't provide the full file path but just the name of files and directories. You have to append each values in the array to the path to your Document Directory.
Something like this:
NSString *documentsDirectoryPath = [NSHomeDirectory() stringByAppendingPathComponent:#"Documents"];
NSString *imagePath = [documentsDirectoryPath stringByAppendingPathComponent:[imageArray objectAtIndex:indexPath.row]];
UIImage *image = [UIImage imageWithContentsOfFile:imagePath];
I suspect, you are not initialising any cells before using (dequequing) one. Initialise your cell, and try again. Good Luck!
PS: by initialising I mean, alloc init your cell.

Creating image thumbnails to be loaded into tableview from files in app directory

I need some help for a problem which I can't solve but I think I am close to the solution. Here is it:
In a version of my app, I was able to populate a tableview (in CellforRowAtIndexPath) with images taken from the Assetlibrary using the following 2 lines:
ALAsset someAsset = [theAssets objectAtIndex:indexPath.row];
[cell.imageView setImage:[UIImage imageWithCGImage:[someAsset thumbnail]]];
Now, I am trying to read image files from the directory and stored in an NSMutableArray. I can see the filenames when I NSLog the NSMutableArray. But how do I now cause the files to be converted into images and displayed in my tableview in the same way I did why using the Assetlibrary? I have tried several times, but the app either crashes or it does not show the image thumbnails in the table view. For example, this statement does not display the image but the app does not crash:
UIImage *anImage = [UIImage imageWithContentsOfFile:[self.listTable objectAtIndex:0]];
When I setImage in the next line, it doesn't work. Someone please help!
UPDATED: The contents of self.listable when I NSLog it is something like this: "19-10-25 276-10-12.jpg",
"19-10-37 276-10-12.jpg",
"19-10-54 276-10-12.jpg",
"19-10-65 276-10-12.mov", etc.
When I NSLog my documents directory, it is: /var/mobile/Applications/8CB1368A-AAE2-4815-BD26-A7B7C8536193/Documents.
Apps can only imageWithContentsOfFile for files located within the app's sandbox (e.g. in Documents, the bundle, etc.) If these files are located in your Documents folder, you get the full path via:
NSString *documentsFolder = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *imageFullPath = [documentsFolder stringByAppendingPathComponent:imageFilename];
You can then use that in imageWithContentsOfFile.
Update:
You asked:
my directoryContents is an NSArray; how do I convert it to NSString and then [documentsFolder stringByAppendingPathComponent ...] and store each fullpath in the NSMutableArray?
You might do something like:
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSArray *filenames = [fileManager contentsOfDirectoryAtPath:documentsDirectory error:nil];
NSMutableArray *paths = [[NSMutableArray alloc] initWithCapacity:[filenames count]];
for (NSString *filename in filenames)
{
[paths addObject:[documentsDirectory stringByAppendingPathComponent:filename]];
}
NSLog(#"%s filenames = %#", __FUNCTION__, filenames);
NSLog(#"%s paths = %#", __FUNCTION__, paths);

iOS Split view controller - changing image in detailViewController

This is another of those "I'm sure there's an easy answer to this" questions, but I find myself baffled.
I'm using the split view controller from the template. I'm successfully passing a NSString to the _detailItem variable, but am unable to use it to create and load an image into an UIImageView (named "stripImage").
It works up until:
[self.stripImage setImage:[UIImage imageNamed: _detailItem]];
If I put a string literal into the same line of code (like #"image20.jpg"), it works fine.
- (void)configureView
{
// Update the user interface for the detail item.
if (self.detailItem) {
NSLog(#"_detailItem is still: %#",_detailItem);
// correctly reports the name of the imagefile (for example: "image20.jpg"
[self.stripImage setImage:[UIImage imageNamed: _detailItem]];
NSLog(#"The image being shown is: %#",self.stripImage.image);
//returns "The image being shown is: (null)"
}
}
Please help keep my head from exploding. Thanks in advance.
... and I've tried it this way:
(in my Master view controller):
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
NSLog(#"Selected row %i",[indexPath row]);
NSString *imageName = [[stories objectAtIndex:[indexPath row]] objectForKey:#"link"];
NSLog(#"The image is: %#", imageName);
// These two work, oddly enough...
self.detailViewController.detailTitle.text = [[stories objectAtIndex:[indexPath row]]
objectForKey:#"title"];
self.detailViewController.detailSubtitle.text = [[stories objectAtIndex:[indexPath row]]
objectForKey:#"subtitle"];
// this one, not so much...
[self.detailViewController loadUpImageWith:imageName];
}
and in my Detail view controller:
- (void)loadUpImageWith:(NSString *)what
{
NSString *path = [[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:[NSString
stringWithFormat:#"strips/%#", what]];
NSLog(#"The file's url is: %#",path);
UIImage *img = [UIImage imageWithContentsOfFile:path];
NSLog(#"The resultant image is: %#",img);
stripImage.image = img;
}
But here's the weird thing... If I replace the variable ("what" in this case) with a string literal:
NSString *path = [[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:[NSString
stringWithFormat:#"strips/%#", #"grumbles300.jpg"]];
... it works, displaying that one image. But I want to be able to use a variable there!!
Help me Obiwan Kenobi! You're my only hope.
Embarrassing operator error.
I was adding a buncha images to the bundle, but it apparently kept track of the folder that contained them, which needed to be added to the file name. I thought UIImage imageNamed: would track down the images, as long as they were contained in the main bundle. Apparently not.
Perhaps this would be useful to someone who's experiencing the same sort of brain fart.
After resolving this, it was easy to do this:
- (void)loadupDetailTitle:(NSString *)title
subtitle:(NSString *)subtitle
image:(NSString *)imageName
{
NSString *path = [#"strips/" stringByAppendingPathComponent:imageName];
stripImage.image = [UIImage imageNamed:path];
detailTitle.text = title;
detailSubtitle.text = subtitle;
}

How to separate images out from Resources in iOS

I'm displaying a set of images in my app. I've got the code working when I load the image from the Resources folder, like so:
- (void)viewDidLoad
{
NSMutableArray *array = [[NSMutableArray alloc] init];
[array addObject:[NSString stringWithFormat: #"pic_a"]];
[array addObject:[NSString stringWithFormat: #"pic_b"]];
[array addObject:[NSString stringWithFormat: #"pic_c"]];
[array addObject:[NSString stringWithFormat: #"pic_d"]];
int index = arc4random() % [array count];
NSString *pictureName = [array objectAtIndex:index];
NSString* imagePath = [ [ NSBundle mainBundle] pathForResource:pictureName ofType:#"png"];
UIImage *img = [ UIImage imageWithContentsOfFile: imagePath];
if (img != nil) { // Image was loaded successfully.
[imageView setImage:img];
[imageView setUserInteractionEnabled:NO];
[img release]; // Release the image now that we have a UIImageView that contains it.
}
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
}
However, if I create an "images" group within the "Resources" group, and put try to load the images from there, the image within the view shows up blank.
[array addObject:[NSString stringWithFormat: #"images/pic_a"]];
[array addObject:[NSString stringWithFormat: #"images/pic_b"]];
[array addObject:[NSString stringWithFormat: #"images/pic_c"]];
[array addObject:[NSString stringWithFormat: #"images/pic_d"]];
I'd like to separate the images out from the nib files and all the other cruft. What's the best way to do that?
Even if you have the images in a separate group within Resources, you can load them by calling the name, e.g. use this one line
UIImage *img = [UIImage imageNamed:[array objectAtIndex:index]];
in place of these three lines:
NSString *pictureName = [array objectAtIndex:index];
NSString* imagePath = [ [ NSBundle mainBundle] pathForResource:pictureName ofType:#"png"];
UIImage *img = [ UIImage imageWithContentsOfFile: imagePath];
You will still fill the array simply by
[array addObject:[NSString stringWithFormat: #"pic_a"]];
If you have both jpg and png files, then you should append .png to the end of the file names. Otherwise, leaving it off is fine.
Try using the imageNamed: method instead of imageWithContentsOfFile:
You need to create a physical folder called images (it should have a blue color instead of the usual yellow color)
Remember that adding groups inside your project it is simply for organization and look within Xcode. You adding a group will not change the fact that the images will be saved in the main bundle. If you are trying to find them using the images group in the string it will not find them.
There are some things you can do to make this work, but in reality you don't need to.

Resources